NodeJS:数据参数必须是string/Buffer/TypedArray/DataView类型,如何修复?

xxb16uws  于 2023-04-20  发布在  Node.js
关注(0)|答案(2)|浏览(372)

这个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不是很熟悉,所以有人能告诉我如何修改这段代码来删 debugging 误吗?

ubof19bj

ubof19bj1#

所以错误是说data(fs.writeFileSync函数的第二个参数)应该是一个字符串或缓冲区...等,但得到的是一个数字。
要解决这个问题,请将第二个参数转换为字符串,如下所示:

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

yb3bgrhw2#

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

相关问题