fs.readfile async 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.readfile
fs.readFile('filename', function read(err, data) {
if (err) {
throw err;
}
var content = data;
console.log(content);
});
Example 4: how to export fs.readFile
var fs = require('fs');
module.exports = {
parseFile: function(file_path, callback) {
fs.readFile(file_path.toString(), 'utf-8', function(err, data) {
if (err) return callback(err);
callback(null, data);
});
}
}
exports.parseFile = function(file_path, callback) {
fs.readFile(file_path.toString(), 'utf-8', callback);
}
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);
})