fs writefile code example
Example 1: How to append to a file in Node?
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
Example 2: writefile in node js
const fs = require('fs');
let lyrics = 'But still I\'m having memories of high speeds when the cops crashed\n' +
'As I laugh, pushin the gas while my Glocks blast\n' +
'We was young and we was dumb but we had heart';
fs.writeFile('2pac.txt', lyrics, (err) => {
if (err) throw err;
console.log('Lyric saved!');
});
Example 3: 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 4: 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 5: writefile in node js
const fs = require('fs');
let writeStream = fs.createWriteStream('secret.txt');
writeStream.write('aef35ghhjdk74hja83ksnfjk888sfsf', 'base64');
writeStream.on('finish', () => {
console.log('wrote all data to file');
});
writeStream.end();
Example 6: 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
}
})