express fs 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: node js write file
const fs = require('fs');
let path = 'ghetto_gospel.txt';
let buffer = new Buffer('Those who wish to follow me\nI welcome with my hands\nAnd the red sun sinks at last');
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'could not open file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function() {
console.log('wrote the file successfully');
});
});
});
Example 3: 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 4: fs.readfile
fs.readFile('filename', function read(err, data) {
if (err) {
throw err;
}
var content = data;
console.log(content);
});
Example 5: fs readfile encoding
fs.readFile('/etc/passwd', 'utf8', callback);