Open In App

How To Remove Blank Lines From a .txt File In Node.js?

Last Updated : 12 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Removing blank lines from a text file is a common task when working with data in text format. Blank lines can occur due to formatting errors, data entry mistakes, or during file generation. Node.js, with its non-blocking I/O and file system capabilities, makes it easy to automate this process.

In this article, we will see how to remove blank lines from a .txt file in Node.js.

Approach To Remove Blank Lines From a .txt File

Here is how we will proceed to remove the blank lines:

  • Read the Content of the File: We will read the file's contents into local memory using the fs.readFile method of Node.js.
  • Process the Content: The content will be divided line-wise, blank lines will be removed and the remaining lines will be combined back.
  • Write the Updated Content Back to the File: Lastly, the original file will be overwritten using fs.writeFile with the new content that has been cleaned.

Steps To Remove Blank Lines From a .txt File

Step 1: Create a basic Node Application folder and initialize the application using

mkdir node-space-remover
cd node-space-remover

Step 2: Initialize the application using the following command.

npm init -y

Create a file named index.js and also put the txt file in which you want to remove spaces.

Folder Structure

eff
Folder Structure

Example: In this example, we will provide a .txt file sample and implement a neat procedure of removing the blank lines from this file in a sequential manner using Node.js:

JavaScript
// Import the file system module
const fs = require('fs');

const fileLocation = 'sample.txt';

// Read the file contents
fs.readFile(fileLocation, 'utf8', (error, fileContent) => {
    if (error) {
        console.error('Error reading the file:', error);
        return;
    }

    const linesArray = fileContent.split('\n');

    const filteredLines = linesArray.filter(line => line.trim() !== '');

    const updatedContent = filteredLines.join('\n');

    // Write the updated content back to the file
    fs.writeFile(fileLocation, updatedContent, 'utf8', (error) => {
        if (error) {
            console.error('Error writing to the file:', error);
            return;
        }
        console.log('Successfully removed blank lines.');
    });
});

Explanation:

  • Read the File: fs.readFile(fileLocation, 'utf8', ...) fetches the text contained in sample.txt using the utf8 character encoding scheme. The content will be returned as a string to the callback function.
  • Process the Content: fileContent.split('\n') cuts the contents of a file into an array of the separate lines of text.
  • linesArray.filter(line => line.trim() !== '') removes all the lines that are either blank or have Douglas aspects and keeps the productive part intact.
  • Write the Updated Content: filteredLines.join('\n') reconstitutes the filtered lines except that it combines them into one string and there is a newline for each of the combinations.
  • fs.writeFile(fileLocation, updatedContent, 'utf8', ...) returns the edited contents back to sample.txt. The error informing is if there is any during writing is logged in the console.

Output

Let's consider the input file 'input.txt' with following content:

input
Input file

After running the code, the input file will be changed to:

output
Remove blank lines from a .txt file in Node.js

Next Article
Article Tags :

Similar Reads