fs writefile javascript code example
Example 1: writefile in node js
// writefile.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';
// write to a new file named 2pac.txt
fs.writeFile('2pac.txt', lyrics, (err) => {
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log('Lyric saved!');
});
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!");
});
// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
Example 4: writefile in node js
// write_stream.js
const fs = require('fs');
let writeStream = fs.createWriteStream('secret.txt');
// write some data with a base64 encoding
writeStream.write('aef35ghhjdk74hja83ksnfjk888sfsf', 'base64');
// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
console.log('wrote all data to file');
});
// close the stream
writeStream.end();
Example 5: 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
}
//file written successfully
})
Example 6: javascript write to file
<script>
const fs = require('fs')
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => {
if (err) throw err;
})
</script>