【问题标题】:NodeJS: Data argument must be of type string/Buffer/TypedArray/DataView, how to fix?NodeJS:数据参数必须是string/Buffer/TypedArray/DataView类型,如何解决?
【发布时间】:2020-09-04 20:11:06
【问题描述】:

此 Node JS 代码来自 this project,我正在努力理解。

// initialize the next block to be 1
let nextBlock = 1

// check to see if there is a next block already defined
if (fs.existsSync(configPath)) {
    // read file containing the next block to read
    nextBlock = fs.readFileSync(configPath, "utf8")
} else {
    // store the next block as 0
    fs.writeFileSync(configPath, parseInt(nextBlock, 10))
}

我收到此错误消息:

Failed to evaluate transaction: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received type number (1)

我对 NodeJS 不太熟悉,谁能向我解释如何更改此代码以消除错误?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    所以错误是说data(fs.writeFileSync 函数的第二个参数)应该是一个字符串或一个缓冲区......等等,而是得到一个数字。

    要解析,将第二个参数转换为字符串,如下所示:

    fs.writeFileSync(configPath, parseInt(nextBlock, 10).toString())
    

    【讨论】:

      【解决方案2】:

      如果数据是 JSON:

      写入文件:

      let file_path = "./downloads/";
      let file_name = "mydata.json";
      
      
      let data = {
          title: "title 1",
      };
      fs.writeFileSync(file_path + file_name, JSON.stringify(data));
      

      从文件中读取:

      let data = fs.readFileSync(file_path + file_name);
      data = JSON.parse(data);
      console.log(data);
      

      【讨论】:

        猜你喜欢
        • 2021-03-16
        • 1970-01-01
        • 2021-08-07
        • 2022-01-21
        • 2021-10-27
        • 2020-12-09
        • 2020-02-06
        • 1970-01-01
        相关资源
        最近更新 更多