How to remove blank lines from a .txt file in Node.js
Removing blank lines from a .txt file in Node.Js is easy. Let’s Understand the concept, First of all, we have to access the .txt file next we need to break the paragraph or sentences into parts by line and store it into an Array and if that’s a blank line then ignore it, After that concat all the elements of the Array and lastly remove the old content with the new modified content.
Take a look at the code and then to the explanation-
//Importing fs module const fs = require('fs'); const Path = 'path/file.txt'; //accessing the file fs.readFile(Path, 'utf8', (err, data)=> { if (err) { console.error(err); return; } //spliting the file data accroding to the line const lines = data.split('\n'); const non_Empty_Lines = []; //removing blank lines and adding the non empty lines to an new array for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (line !== '') { nonEmptyLines.push(line); } } //concatinating the new data const modified_data = nonEmptyLines.join('\n'); //change the old data to new non empty lines data fs.writeFile(filePath, modifiedContent, 'utf8', function(err) { if (err) { console.error(err); return; } console.log('Blank lines removed successfully!'); }); });
First, we need to import the fs module to access the .txt to read and write the file data. In Node.Js fs.readFile reads the file content. Error handling must be added to find if the program finds any kind of difficulties to access the file. The content is then split with an in-built method of Node.Js split()
, ‘\n’ in the split is referring that the split of the content or data by every time the line change and add it to an Array(lines).
Then each element of the Array is then accessed and modified by removing white spaces by a method(trim()
), and if the line is blank then the Array element will be an empty string(” “). After trimming the Array the elements are then added to a new Array(non_Empty_Lines) with a condition that if the element is empty string then ignore it.
now the new modified non-empty line data is ready to remove the old data with blank lines, it is done by the writeFile method provided by the fs module.
Leave a Reply