Node.js Writing Text File using File System fs Module
Using Node.js built-in file system fs module to create and write content to a text file.
Write text to file using fs.appendFile() method
The fs.appendFile() method to append text to an existing file.
It will create a new file if the file does not exist.
Example code below will create new file named test.txt and append text ‘Welcome to toricode.com’ to it.
let fs = require('fs');
fs.appendFile('test.txt', 'Welcome to toricode.com', function(err){
if(err) {
console.log('Error!');
console.log(err);
} else {
console.log('File Saved!');
}
});
Save code above to create_file.js file and execute the code.
node create_file.js
File Saved!
After code executed we will get new file named test.txt with content as below.
Welcome to toricode.com
Write text to file using fs.writeFile() method
The fs.writeFile() method to override the existing file with a new text content.
It will create a new file if the file does not exist.
let fs = require('fs');
fs.writeFile('test.txt', 'Welcome to toricode.com', function(err){
if(err) {
console.log('Error!');
console.log(err);
} else {
console.log('File Saved!');
}
});
Save code above to create_file.js file and execute the code.
node create_file.js
File Saved!
After code executed we will get new file named test.txt with content as below.
Welcome to toricode.com
Open and write text to file using fs.open() and fs.write() methods
The code example below to show you how to use fs.write() method to write data to a file bytes by bytes.
Firstly we need to open file by fs.open() method, the call back function will provide file descriptor fd to use it in fs.write() method.
In order to write text using fs.write() we need to convert string to buffer using Buffer.from() method.
let fs = require('fs');
fs.open('test.txt', 'w', function(err, fd) {
if(err) {
console.log('Error!');
console.log(err);
} else {
let data = Buffer.from('Welcome to toricode.com');
let position = 0;
let offset = 0;
let length = data.length;
fs.write(fd, data, offset, length, position, function(err) {
if(err) {
console.log("Error writing file");
console.log(err);
} else {
console.log("File saved!");
}
});
}
});
Execute the code.
node create_file.js
File saved!
The test.txt created
Welcome to toricode.com