how to open file with require fs nodejs code example
Example 1: node open file
const fs = require("fs");
fs.readFile(__dirname + "/data.txt", (error, data) => {
if(error) {
throw error;
}
console.log(data.toString());
});
Example 2: read file in nodejs using fs
let myFile = "./myText.txt";
const fs = require("fs");
app.all('/test', async (req, res) => {
try {
const readData = fs.readFileSync(myFile, 'utf8');
if (readData) {
res.send(readData)
}
} catch (error) {
res.send("something is wrong", error)
}
})