node js fs.readfile code example
Example 1: nodejs readfile
const fs = require('fs');
fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err);
return
}
console.log(data);
});
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)
}
})
Example 3: javascript fs read
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
Example 4: fs readfile encoding
fs.readFile('/etc/passwd', 'utf8', callback);