I am trying to append a string to the log file. But writeFile erases the contents every time it writes a string.
fs.writeFile('log.txt', 'Hello Node', function (err) { if (err) throw err; console.log('It\'s saved!'); }); // => message.txt erased, contains only 'Hello Node'
How can any idea do this in a simple way?
#1 building
For an occasional append, you can use appendFile, which creates a new file handle each time it is called:
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');
However, if you repeatedly append to the same file, it is better to Reuse file handle .
#2 building
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a') fs.writeSync(fd, 'contents to append') fs.closeSync(fd)
#3 building
Node.js 0.8 has fs.appendFile:
fs.appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); });
#4 building
This is the complete script. Fill in the filename and run it, it should work! This is about the logic behind the script Video tutorial .
var fs = require('fs'); function ReadAppend(file, appendFile){ fs.readFile(appendFile, function (err, data) { if (err) throw err; console.log('File was read'); fs.appendFile(file, data, function (err) { if (err) throw err; console.log('The "data to append" was appended to file!'); }); }); } // edit this with your file names file = 'name_of_main_file.csv'; appendFile = 'name_of_second_file_to_combine.csv'; ReadAppend(file, appendFile);
#5 building
You need to open it and write it.
var fs = require('fs'), str = 'string to append to file'; fs.open('filepath', 'a', 666, function( e, id ) { fs.write( id, 'string to append to file', null, 'utf8', function(){ fs.close(id, function(){ console.log('file closed'); }); }); });
Here are some links to help explain the parameters
Edit: this answer is no longer valid. Please check the new fs.appendFile Method.