NodeJS:数据参数必须为string / Buffer / TypedArray / DataView类型,如何解决?

时间:2020-05-18 21:50:38

标签: node.js

此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不太熟悉,所以谁能向我解释如何更改此代码以消除错误?

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

如果数据是 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);