温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.muo.com/node-write-files-learn/
点击访问原文链接

Learn How to Write Files in Node

Learn How to Write Files in Node Menu Sign in now Close Trending Submenu Productivity Android Smart TVs Networking Windows 11 Entertainment PC & Mobile Submenu Windows2 Linux Android Apple Technical Submenu Tech Explained Security Software Submenu Productivity Internet Creative Screen Submenu Entertainment Streaming Home Submenu Smart Home Home News Sign in Newsletter Menu Follow Followed Like More Action Sign in now Productivity Android Smart TVs Networking Windows 11 Entertainment Close
Learn How to Write Files in Node No attribution required. Photo from Pexels Follow Followed Like Link copied to clipboard Add us on By  Mary Gathoni Published Jun 2, 2022, 7:00 AM EDT Mary writes for the programming section and has been doing so for the past two years. Her educational background is in Computer Science and Physics. Sign in to your MakeUseOf account

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
Recommended How to Read CSV Files With Node.js I disabled Windows Prefetch to save RAM — I was actually making my PC slower Firefox is better than Chrome, but this third option is miles ahead I found the hidden Android setting that stops your phone from dropping to dead Wi-Fi Join Our Team Our Audience About Us Press & Events Media Coverage Contact Us Follow Us Advertising Careers Terms Privacy Policies MakeUseOf is part of the Valnet Publishing Group Copyright © 2026 Valnet Inc.

Learn How to Write Files in Node,AI智能索引,全网链接索引,智能导航,网页索引

    Find out about Node