node.js - 无法使用 protobuf.js 加载 protobuf 消息
问题描述
我试图将 proto 消息与 protobuf.js 一起使用,对它们进行编码并将它们发送到 RabbitMQ 消息代理。我的项目中有以下子文件夹:
- model
- protos
- transactions.proto
- RabitMQ.js
- routes
- rmq-api.js
我在 rmq-api.js 文件中添加了一个执行以下操作(使用 express)的路由:
const RabbitMQ = require('../model/RabbitMQ');
router.post('/api/transactions' ,function (req,res,next) {
RabbitMQ.PublishTransactionsMessage(DummyMessage).then(() => {
res.status(200).send({message: "OK :)"});
}).catch((e) => {
res.status(500).send({error:e.message});
});
});
在 RabitMQ.js 文件中,我有以下代码:
module.exports = {
PublishTransactionsMessage: function(message) {
return new Promise((resolve, reject) => {
amqp.connect(RabbitMQConfig.url, function (error, connection) {
if (error) {
console.error("Could not connect to the rabbit message broker on {0} - " +
"Check connection please and try again".format(RabbitMQConfig.url));
console.error("Error message - {0}".format(error));
reject(error)
}
connection.createChannel(function(error, channel) {
if (error) {
console.error("Could Create channel - {0}".format(error.message));
reject(error)
}
const queue = RabbitMQConfig.queue;
channel.assertQueue(queue, {
durable: true
});
// Convert Message to protobuff
protobuf.load("./protos/transactions.proto").then((err, root) => {
if (err) {
reject(err);
}
let ScraperMessageResult = root.lookupType("transactions.ScraperMessageResult");
const errMsg = ScraperMessageResult.verify(message);
if (errMsg)
reject(errMsg);
let buffer = ScraperMessageResult.encode(message).finish();
channel.sendToQueue(queue, buffer);
console.log(`Sent ${message} to queue: ${queue}`);
resolve()
}).catch((err) => {
reject(err);
});
});
});
});
},
};
在上面显示的代码行中:
protobuf.load("./protos/transactions.proto").then((err, root) => {
我一直遇到以下错误:
在这个 catch 块内:
}).catch((err) => {
reject(err);
});
这似乎是一个非常简单的问题,但是我在网上没有找到任何东西,所以我可能在这里遗漏了一些非常简单的东西。PS 我尝试使用 __dirname + "/protos/transaction.proto" 仍然无法让它工作。请帮我解决这个问题。
解决方案
问题是您的函数不查看 dist 目录,
await protocolBuffer.load(__dirname + '/item.proto'); should look there,
并且您还需要使用 copy/cp 命令手动复制文件,您可以将其添加为包 json 脚本的一部分,如下所示:
"build": "nest build && COPY src\\reading_list\\protocol_buffer\\*.proto dist\\reading_list\\protocol_buffer\\"
推荐阅读
- javascript - Cheerio 从 .text() 获取包含中断和 H 标记的内容
- laravel - 如何在控制器中使用 Laravel 中的自定义保护登录用户
- laravel - 带有搜索错误链接的laravel分页
- node.js - React Native:你需要哪些全局包保持最新?
- logging - Scala Cats:如何测试日志记录与如何登录生产代码
- tensorflow - 使用 Tensorflow/Keras 求解微分方程的自定义损失函数问题
- java - 从字符串数组中删除元素后,如何减少元素的索引?
- css - 在 D3 中,如何在使用变换旋转布置其位置后旋转字母?
- python - 为什么 not (a and b) 与 not a and not b 不一样?
- typescript - 打字稿:对象数组中的联合类型