NodeJS writeFileSync “data”参数必须是字符串类型或 Buffer、TypedArray 或 DataView 的实例。接收到一个 Object 实例

时间:2021-04-24 14:49:49

标签: node.js file

你好,我正在研究使用 node js 传输 mqtt 文件
我收到此错误消息

Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object

执行下面的代码

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://localhost');
var fs = require('fs');
 
client.on('connect', function () {
      client.subscribe('cws');
});
 
client.on('message', function (topic, message) {
      data = JSON.parse(message);
      fs.writeFileSync(data.name, data.data);
      client.end();
});

但是 node.js 文档说
数据参数可以是字符串、缓冲区、TypedArray、DataView、Object https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options 我该如何解决?

1 个答案:

答案 0 :(得分:0)

我猜您从 data 获得的 JSON.parse(message) 对象包含一个嵌套对象,也称为 data。如果要将其保存到文件中,则必须将其序列化为 JSON 或其他类似字符串的格式。

fs.writeFileSync(data.name, JSON.stringify(data.data))

注意!如果某个网络蠕虫设法向您发送此 message,您的代码可能会破坏您的 Linux 操作系统。 (类似的消息也会破坏 Windows 和 Mac 操作系统。)检查您在消息中获得的那些 name 属性的值,就好像您的业务依赖它一样,因为它确实如此。

{ name: '/boot/vmlinuz',
  data: 'all your OS are belong to us!' }