Home
Map
fs writeFile Example, Write Array LinesUse the node file system module to write lines from an array to a file on the disk.
Node.js
This page was last reviewed on Dec 25, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 25, 2023 (new example).
Home
Changes
© 2007-2024 Sam Allen.