@google-cloud/speech - Error: ENOENT: no such file or directory, open 'protos.json

@google-cloud/speech - Error: ENOENT: no such file or directory, open 'protos.json

我正在尝试使用 google 云语音发送短信 api。

我正在使用示例 google 代码,当我创建客户端对象时出现此错误。

{ 
   "errno":-2,
   "syscall":"open",
   "code":"ENOENT",
   "path":"protos.json",
   "stack":"Error: ENOENT: no such file or directory, open 'protos.json'\n    at Object.openSync (fs.js:440:3)\n    at Object.readFileSync (fs.js:342:35)\n    at fetch (transcript-server-js/node_modules/protobufjs/src/root.js:160:34)\n    at Root.load (/transcript-server-js/node_modules/protobufjs/src/root.js:194:13)\n    at Root.loadSync (/transcript-server-js/node_modules/protobufjs/src/root.js:235:17)\n    at Object.loadSync (/transcript-server-js/node_modules/@grpc/proto-loader/build/src/index.js:221:27)\n    at GrpcClient.loadFromProto /transcript-server-js/node_modules/google-gax/src/grpc.ts:165:40)\n    at GrpcClient.loadProto (/transcript-server-js/node_modules/google-gax/src/grpc.ts:199:17)\n    at new SpeechClient /transcript-server-js/lib/webpack:/src/v1/speech_client.ts:135:28)\n    at createText$ (/transcript-server-js/lib/webpack:/src/transcriptGenerator.js:50:18)"
}

这是代码

const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
const results = await storage.getBuckets();
const speech = require('@google-cloud/speech');
const client = new speech.SpeechClient();

google 云存储 api 有效。

有人可以帮助我吗?

谢谢

我运行和@google-cloud/firestore一起进入这个。 @google-cloud/firestore@google-cloud/speech都使用相同的机制来加载protos.json,所以我的解决方案应该与这里相关。

这发生在我身上,因为 webpack 正在将 @google-cloud/firestore 包构建到我的包中。 @google-cloud/firestore 包使用 __dirname 来查找 protos.json。由于 @google-cloud/firestore 代码在我的包中,因此 __dirname 变量被设置为我的包的目录,而不是包含 protos.json.

node_modules/@google-cloud/firestore/ 子目录

可能的修复 #1

在你的 webpack 配置中设置这个来告诉 webpack 设置 __dirname:

的值
    node: {
      __dirname: true,
    }

https://webpack.js.org/configuration/node/

可能的修复 #2

更新您的 webpack 配置以从您的包中排除 @google-cloud/speech

一种方法是使用 webpack-node-externals 包从 node_modules 目录中排除所有依赖项:

var nodeExternals = require('webpack-node-externals')
...
module.exports = {
  ...
  externals: [nodeExternals()],
  target: 'node',
  ...
};

非常感谢 Gabriel Deal。 我在 firestore 包中遇到了和你一样的问题。我从您的解释中理解了为什么会发生这种情况。不幸的是,这些修复对我没有帮助。所以我不得不换一个。我将 protos.json 文件复制到它在我的 dist 文件夹中搜索的路径。

  1. protos.json 从 node_modules 复制到一个文件夹(我将其命名为 external_files )
  2. webpack.config.js 中将 protos.json 文件从 external_files 目录复制到它正在搜索的路径(在我的例子中它正在 node_modules/google-gax/protos 中搜索)。使用插件 CopyWebpackPlugin 完成该工作,如下所示。
module.exports = {
.
.
.
    plugins: [
        new CopyWebpackPlugin([
            { from: "external_files/protos.json", to: "dist/node_modules/google-gax/protos" }
        ])
    ]
}