how to read file in node js code example
Example 1: read file node
const fs = require("fs");
const content = fs.readFileSync("./my_file.txt");
console.log(content.toString());
Example 2: node open file
const fs = require("fs");
fs.readFile(__dirname + "/data.txt", (error, data) => {
if(error) {
throw error;
}
console.log(data.toString());
});
Example 3: read a file nodejs
const fs = require('fs');
fs.readFile('my-file.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
Example 4: 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 5: 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 6: nodejs open file
fs = require('fs')
fs.readFile('/etc/hosts', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});