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:

JavaScript
const fs = require('fs');
const outputFilePath = 'output.txt';

To write to a file, we'll use fs.writeFileSync, which overwrites the file if it already exists or creates a new one.

JavaScript
fs.writeFileSync(outputFilePath, "Hello, World!\nThis is a new line of text.\n", 'utf-8');
console.log(`Text written to ${outputFilePath} using 'w' mode.`);

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:

Hello, World!
This is a new line of text.

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:

JavaScript
fs.appendFileSync(outputFilePath, "Appending another line of text.\n", 'utf-8');
console.log(`Text appended to ${outputFilePath} using 'a' mode.`);

This appends the new line to the existing file content, preserving all original data.

Running this results in:

Hello, World!
This is a new line of text.
Appending another line of text.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal