node js fs module code example
Example 1: node open file
const fs = require("fs");
fs.readFile(__dirname + "/data.txt", (error, data) => {
if(error) {
throw error;
}
console.log(data.toString());
});
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: fs writefile node
const fs = require('fs')
const content = 'Some content!'
fs.writeFile('/Users/joe/test.txt', content, err => {
if (err) {
console.error(err)
return
}
})
Example 5: writeFileSync
var fs = require('fs');
fs.writeFile('/tmp/hello.txt', 'Hello world!', function(err) {
if(err) return console.error(err);
});
var buffer = new Buffer([ 0x48, 0x65, 0x6c, 0x6c, 0x6f ]);
fs.writeFile('binary.txt', buffer, function(err) {
if(err) return console.error(err);
});
Example 6: fs readfile encoding
fs.readFile('/etc/passwd', 'utf8', callback);