Writing and Appending Text Files in JavaScript Using Node.js
Introduction to Writing to Files in JavaScript
In this lesson, we're exploring the powerful capabilities of writing to files using JavaScript with Node.js. File writing is an essential skill in programming, allowing you to store data permanently, log information, and communicate with other systems or users. We'll delve into various modes of file operations using the fs (File System) module, focusing on write (using fs.writeFileSync), append (using fs.appendFileSync), and briefly reading (using fs.readFileSync) to confirm our output.
Understanding the Write Mode
Let's begin by exploring how we can write to a file in JavaScript using Node.js. The write mode is used to create a new file or overwrite an existing one.
First, we define the path for the file we want to write to:
To write to a file, we'll use fs.writeFileSync, which overwrites the file if it already exists or creates a new one.
Here, we write multiple lines of text, ensuring each ends with a newline character \n to separate lines. In contrast to some other languages, JavaScript automatically closes the file, so no explicit close is needed. If the function is executed again, the previous content will be replaced, emphasizing the session-specific nature of writing.
When executed, output.txt will contain:
Being synchronous, writeFileSync blocks the execution of subsequent code until the file operation is complete. While this ensures consistency in single-threaded applications, it can slow down performance in scenarios requiring frequent writes.
Demystifying the Append Mode
In write mode, any existing content in the file is erased upon opening. This is convenient for starting fresh or completely overwriting existing content. However, if you intend to retain existing data while adding new content, append mode comes into play, utilizing fs.appendFileSync.
To append text to the end of the file:
This appends the new line to the existing file content, preserving all original data.
Running this results in:
