Examples to write a file, including:
- Write a file asynchronously
fs.writeFile(filename, ...)
, writes data to a file, replacing the file if it already existsfs.appendFile()
, appends data to a file
- Write a file synchronously
fs.writeFileSync(filename, ...)
fs.appendFileSync()
- Write a file frequently in an effect way
Write a file asynchronously
Method 1 — fs.writeFile()
fs.writeFile(filename, data[, options], callback)
asynchronously writes data to a file, replacing the file if it already exists.
const fs = require('fs');
function writeFileAsync(file, data) {
// The file will be created if it does not yet exist.
fs.writeFile(file, data, err => { // The default encoding is 'utf8'
if (err) {
console.error(err);
}
console.log('Finished: the data was appended to file!');
});
}
fs.writeFile():
It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream() is recommended.
Similarly to fs.readFile – fs.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using fs.createWriteStream().
The part “Write a file frequently in an effect way” in the end of the file gives an example using
fs.createWriteStream()
.
const file = './test.txt';
writeFileAsync(file, 'spring 春');
writeFileAsync(file, 'summer 夏');
// The contents of test.txt is uncertain, it may be 'spring 春' or 'summer 夏'.
Method 2 — fs.appendFile()
fs.appendFile()
asynchronously append data to a file, creating the file if it does not yet exist.
const fs = require('fs');
function appendFileAsync(file, data) {
fs.appendFile(file, data, (err) => { // The default encoding is 'utf8'
if (err) throw err;
console.log('Finished: the data was appended to file!');
});
}
Write a file synchronously
Method 1 — fs.writeFileSync()
const fs = require('fs');
function writeFileSync(file, data) {
try {
fs.writeFileSync(file, data); // The default encoding is 'utf8'
} catch (err) {
console.error(err);
}
}
Method 2 — fs.appendFileSync()
fs.appendFileSync()
synchronously append data to a file, creating the file if it does not yet exist.
const fs = require('fs');
function appendFileSync(file, data) {
try {
fs.appendFileSync(file, data); // The default encoding is 'utf8'
console.log('Finished: the data was appended to file!');
} catch (err) {
console.error(err);
}
}
Write a file frequently in an effect way
Here is an tiny command line program which is inspired from readline – tiny-cli. In this program, when the user enters a sentence, the program writes the contents to a file.
const fs = require('fs');
const readline = require('readline');
function noteCLI() {
const file = './note.txt'; // Run in git terminal
const writer = fs.createWriteStream(file);
// The file will be created if it does not yet exist.
writer.on('error', (err) => {
console.error(`Error occured: ${err.message}`);
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'note> ',
});
rl.prompt();
rl.on('line', (line) => {
line = line.trim()
switch (line) {
case 'exit':
rl.close();
break;
default:
writer.write(`${line}n`)
rl.prompt()
break;
}
}).on('close', () => {
console.log('Bye!');
// If 'end()' has been called, the 'finish' event will be emitted when all
// data has been flushed to the file
writer.on('finish', () => {
console.log('Finished: all notes have been written to the file!');
});
// The 'close' event is emitted when the stream and any of its underlying resources
// (a file descriptor, for example) have been closed. The event indicates that no more
// events will be emitted, and no further computation will occur.
writer.on('close', () => {
process.exit(0);
});
// Signals that no more data will be written to stream.
writer.end();
});
}
noteCLI();
The effect:
$ node file.js
note> hello
note> world
note> bye
note> exit
Bye!
Finished: all notes have been written to the file!
Tiny CLI example with
readline
readline – tiny-cli provides an example which illustrates how to use
readline
module to create a command line program. Below code made a small change :const rl = require('readline'); function tinyCLI() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: 'OHAI> ', }); rl.prompt(); rl.on('line', (line) => { line = line.trim() switch (line) { case 'hello': console.log('world!'); break; case 'exit': rl.close(); default: console.log(`Say what? I might have heard '${line}'`); break; } rl.prompt(); }).on('close', () => { console.log('Have a great day!'); process.exit(0); }); } tinyCLI();
Resource
- [node:fs](File system | Node.js v19.8.1 Documentation)
- node:stream
- How To Work with Files Using Streams in Node.js
Gives a complicated command line program using
fs.createWriteStream()
to handle file save, file copy, etc.More topics in the site: How To Handle Command-line Arguments in Node.js Scripts and How To Create Interactive Command-line Prompts with Inquirer.js.