Node provides different options for writing to files in your system through the built-in fs module. These include writeFile(), appendFile(), and createWriteStream().
Like many languages, Node.js lets you choose between overwriting an existing file or appending to it. You should also learn about the tradeoffs between writing a file in one go and streaming it.
Using writeFile()writeFile() is perhaps the easiest method you can use to write a file in Node.
fs.writeFile(filename, data, callback)
Here is an example showing how to create a plain text file using writeFile(). You can of course create other file types such as CSV or JSON.
const fs = require("fs")
fs.writeFile("test.txt", "New content", err => {
if (err) {
console.log(err)
}
});
writeFile() supports async/await do instead of using callbacks like in the example above, you can create the file as follows.
const fs = require("fs").promises
async function writeToFile() {
try {
await fs.writeFile("test.txt", "New cont")
} catch (err) {
console.log(err);
}
}
writeToFile()
By default, writeFile() works by replacing the contents of the specified file with new content if the file exists. There are however flags you can use to override this functionality such as:
r+ - opens the file to read and write. w+ - opens the file to read and write at the beginning of the file a - opens the file to write at the end of the file. a+ - opens the file to read and write at the end of the file.For example, you can use the a+ flag like this:
const fs = require("fs")
fs.writeFile("test.txt", "Newer content", { flag: "a+" }, err => {
if (err) {
console.log(err)
}
});
There are many other file system flags that you can learn about in the Node documentation for the fs module.
The fs module also provides writeFileSync, the synchronous version of writeFile().
const fs = require("fs")
fs.writeFileSync("test.txt", "Newer content", { flag: "a+" }, err => {
if (err) {
console.log(err)
}
});
Using createWriteStream()
The downside of using writeFile() is that you have to store all the contents of the file at once which is not scalable for large files. createWriteStream() however, supports sequential writing. This means you can write one chunk of data to a file at a time. Here is the general system for creating a writable stream.
fs.createWriteStream(path, options)
The code below writes data to a text file using streams
const fs = require("fs")
// create a writable stream
let writeableStream = fs.createWriteStream("test.txt")
// Write to the file using the writable stream
writeableStream.write("New content");
Here is another example showing how you can pipe data to the writable stream. This program writes all the input from the terminal to the test.txt file as long as the terminal is open.
const fs = require("fs")
let writableStream = fs.createWriteStream("test.txt");
process.stdin.pipe(writableStream);
If you run this program from the command line, you can quit it with Ctrl + d or Ctrl + c.
You can also write from another file to the writable stream. Consider the following example:
const fs = require("fs")
let readableStream = fs.createReadStream("test.txt");
let writableStream = fs.createWriteStream("test2.txt");
readableStream.on("data", function(chunk) {
writableStream.write(chunk);
});
Creating a readable stream of the file you want to copy allows you to read its contents in chunks. So for each chunk received, the program will write to the destination file.
Using appendFile()appendFile() is a straightforward method of adding content to the end of the file. Here is an example.
const fs = require("fs")
fs.appendFile("test.txt", "added content", err => {
if (err) {
console.error(err);
}
});
You can also use async/await.
const fs = require("fs").promises
async function appendToFile() {
try {
await fs.appendFile("test.txt", "added content")
} catch (err) {
console.log(err);
}
}
appendToFile()
Like writeFile(), appendFile also has a synchronous version:
fs.appendFileSync("test.txt", "added content");
Use Streams to Write Large Files
This article discussed several approaches to writing files in Node. While writeFile() is very straightforward, it is better suited for small file sizes since it does not allow sequential writes. If you are dealing with large files, it is better to use writable streams.
Close