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.
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.
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.
string
elements. These will form the contents of each line in the text file.join()
function on the array. This returns a string
with each element separate a newline character.fs.writeFile
receives 2 arguments—we pass it the string
of the file contents, and a lambda expression that handles errors.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
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.