1// writefile.js
2
3const fs = require('fs');
4
5let lyrics = 'But still I\'m having memories of high speeds when the cops crashed\n' +
6 'As I laugh, pushin the gas while my Glocks blast\n' +
7 'We was young and we was dumb but we had heart';
8
9// write to a new file named 2pac.txt
10fs.writeFile('2pac.txt', lyrics, (err) => {
11 // throws an error, you could also catch it here
12 if (err) throw err;
13
14 // success case, the file was saved
15 console.log('Lyric saved!');
16});
17
1const fs = require('fs');
2
3fs.writeFile("/tmp/test", "Hey there!", function(err) {
4 if(err) {
5 return console.log(err);
6 }
7 console.log("The file was saved!");
8});
9
10// Or
11fs.writeFileSync('/tmp/test-sync', 'Hey there!');
1const fs = require('fs');
2
3fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
4 if (err) {
5 console.error(err);
6 return
7 }
8 console.log(data);
9});
1const fs = require('fs');
2
3fs.readFile('file.txt', 'utf-8', (err, data) => {
4 if(err) {
5 throw err;
6 }
7 console.log(data);
8});
9
1// write_stream.js
2
3const fs = require('fs');
4
5let writeStream = fs.createWriteStream('secret.txt');
6
7// write some data with a base64 encoding
8writeStream.write('aef35ghhjdk74hja83ksnfjk888sfsf', 'base64');
9
10// the finish event is emitted when all data has been flushed from the stream
11writeStream.on('finish', () => {
12 console.log('wrote all data to file');
13});
14
15// close the stream
16writeStream.end();
17
1fs.readFile('filename', function read(err, data) {
2 if (err) {
3 throw err;
4 }
5 var content = data;
6
7 console.log(content);
8
9});