NodeJS:数据参数必须是字符串/缓冲区/TypedArray/DataView 类型,如何解决?

use*_*326 12 node.js

这个 Node JS 代码来自我试图理解的这个项目

// 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))
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

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)
Run Code Online (Sandbox Code Playgroud)

我对 NodeJS 不太熟悉,所以有人可以向我解释如何更改此代码以消除错误吗?

Man*_*ddy 22

如果数据是 JSON:

写入文件:

let file_path = "./downloads/";
let file_name = "mydata.json";


let data = {
    title: "title 1",
};
fs.writeFileSync(file_path + file_name, JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)

从文件中读取:

let data = fs.readFileSync(file_path + file_name);
data = JSON.parse(data);
console.log(data);
Run Code Online (Sandbox Code Playgroud)


Gha*_*ani 13

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

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

fs.writeFileSync(configPath, parseInt(nextBlock, 10).toString())
Run Code Online (Sandbox Code Playgroud)