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!');
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
1// append_file.js
2
3const fs = require('fs');
4
5// add a line to a lyric file, using appendFile
6fs.appendFile('empirestate.txt', '\nRight there up on Broadway', (err) => {
7 if (err) throw err;
8 console.log('The lyrics were updated!');
9});
10
1// fs_write.js
2
3const fs = require('fs');
4
5// specify the path to the file, and create a buffer with characters we want to write
6let path = 'ghetto_gospel.txt';
7let buffer = new Buffer('Those who wish to follow me\nI welcome with my hands\nAnd the red sun sinks at last');
8
9// open the file in writing mode, adding a callback function where we do the actual writing
10fs.open(path, 'w', function(err, fd) {
11 if (err) {
12 throw 'could not open file: ' + err;
13 }
14
15 // write the contents of the buffer, from position 0 to the end, to the file descriptor returned in opening our file
16 fs.write(fd, buffer, 0, buffer.length, null, function(err) {
17 if (err) throw 'error writing file: ' + err;
18 fs.close(fd, function() {
19 console.log('wrote the file successfully');
20 });
21 });
22});
23