Home
Node.js
fs writeFile Example, Write Array Lines
Updated Dec 25, 2023
Dot Net Perls
WriteFile. Sometimes in Node programs we need to write a file to the disk. We usually need to build up the data in memory, and string methods can be used for this.
fs readFile
With the node fs module, we can access methods on the fs type—this refers to the file system. We can invoke writeFile to write a file with the string data to the disk.
Example. Here we have a simple program that has an array, and writes it to a text file. The elements are in the array are separated with a newline character in the file.
Step 1 We create a new array of 3 string elements. These will form the contents of each line in the text file.
Array
Step 2 We invoke the join() function on the array. This returns a string with each element separate a newline character.
Step 3 The fs.writeFile receives 2 arguments—we pass it the string of the file contents, and a lambda expression that handles errors.
Step 4 In the lambda expression, we test to see if the error value is present. If so, we log it to the console.
const fs = require("node:fs"); // Step 1: create the lines in an array. let lines = ["One", "two", "three"]; // Step 2: merge the lines with the join function. let content = lines.join("\n"); // Step 3: call writeFile to write the lines to the file. fs.writeFile("example-node.txt", content, err => { // Step 4: print an error if one occurs. if (err) { console.error(err); } console.log("WRITTEN"); });
WRITTEN
WriteFileSync. For simpler code, we can use writeFileSync. This does not require a callback method, and it probably is most useful when any possible errors returned are not important.
const fs = require("node:fs"); // Write a string to a file with writeFileSync. let content = "Even more example content"; fs.writeFileSync("programs/example2.txt", content); console.log("DONE");
DONE
Summary. With Node.js, we have powerful modules that can perform actions on the file system. We can read and write files—and use JavaScript methods to create the data.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 25, 2023 (new example).
Home
Changes
© 2007-2025 Sam Allen