'NodeJS: Data argument must be of type string/Buffer/TypedArray/DataView, how to fix?
This Node JS code is from this project which I'm trying to understand.
// 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))
}
I get this error message:
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)
I'm not too familiar with NodeJS, so could anyone explain to me how I can change this code to remove the error?
Solution 1:[1]
So the error is saying the data (second argument of the fs.writeFileSync function) should be a string or a buffer...etc but instead got a number.
To resolve, convert the second argument to string as shown:
fs.writeFileSync(configPath, parseInt(nextBlock, 10).toString())
Solution 2:[2]
If data is JSON:
Write to file:
let file_path = "./downloads/";
let file_name = "mydata.json";
let data = {
title: "title 1",
};
fs.writeFileSync(file_path + file_name, JSON.stringify(data));
Read from file:
let data = fs.readFileSync(file_path + file_name);
data = JSON.parse(data);
console.log(data);
Solution 3:[3]
In my case "data" event was not executing, i got it fixed my giving the "name" attribute to my input tag in html.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ghassan Maslamani |
| Solution 2 | Manohar Reddy Poreddy |
| Solution 3 | sarma senagavaram |
