Search code examples
javascriptnode.jspromisemutation

Remove line from file without mutating the buffer variable in node js


I am new to Nodejs

I have written a function that reads contents from a file and stores into a variable as an array. And finally I am mutating the variable and writing it to a file. See below:

function(file, item) {
   return fs.readLine(file).then(function(contents) {
       var data = contents.split(/\n/);
       data.splice(data.indexOf(item), 1);
       return fs.writeFile(file, data.join(/\n/));
});
}

Is there a way to do the same without mutating the variable or even having had to store the contents of a file into a variable and delete it in node js?

Thanks


Solution

  • If you don't want to mutate the variable with data.splice() then you can use data.slice() that doesn't mutate the original array. See the docs:

    Also instead of reading the contents of the file into a variable, you can create a readable stream and filter out the line that you don't want.

    See how I created my filt module that filters lines of standard input:

    The source code and a lot of examples are on GitHub:

    Basically what you can do here is - using the handy split module - something like this:

    fs.createReadStream(file).pipe(split()).on('data', (line) => {
        // if line is something ... etc.
    });