fs node js read file code example
Example 1: read file node
const fs = require("fs");
const content = fs.readFileSync("./my_file.txt");
console.log(content.toString());
Example 2: readfilesync
const fs = require('fs')
try {
const data = fs.readFileSync('/Users/joe/test.txt', 'utf8')
console.log(data)
} catch (err) {
console.error(err)
}
Example 3: 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 4: node read file sync
fs.readFileSync('<directory>');
fs.readFileSync('<directory>');