This Node JS code is from this project (https://replit.com/@scip10/filledge#index.js).
I got
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received type number (NaN)
I think the error comes from
app.get('/', (req, res) => {
const count = readFileSync('./count.txt','utf-8');
console.log('count ',count)
const newCount = parseInt(count) 1
writeFileSync('./count.txt', newCount);
I'm not too familiar with NodeJS, so please could anyone explain to me how I can change this code to remove the error?
I expected a localhost web page saying
Welcome to my Website!
This site has been viewed x times
i tried using .tostring() but it just merge strings which 1 1=11.
CodePudding user response:
"The "data" argument must be of type string" so you have to convert newCount to string.
const { readFileSync, writeFileSync } = require("fs");
const express = require("express");
const app = express();
app.get("/", (req, res) => {
const count = readFileSync("./count.txt", "utf-8");
console.log("count ", count);
const newCount = parseInt(count) 1;
writeFileSync("./count.txt", newCount.toString());
res.send(`
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<meta name='viewport' content='width=device-width, initial-scale=1' />
<title>hosted by Rasberry Pi</title>
</head>
<body>
<h1>Welcome to my Website!<h1>
<p>This site has been viewed ${newCount} times</p>
</body>
</html>
`);
});
app.listen(5000, () => console.log("http://localhost:5000/"));