js readfilesync code example
Example 1: readfilesync
const fs = require('fs')
try {
const data = fs.readFileSync('/Users/joe/test.txt', 'utf8')
console.log(data)
} catch (err) {
console.error(err)
}
Example 2: 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 3: fs.writefile
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
Example 4: node read file sync
fs.readFileSync('<directory>');
fs.readFileSync('<directory>');
Example 5: readfile async nodejs
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
function getStuff() {
return readFile('test');
}
getStuff().then(data => {
console.log(data);
})