Home > Software engineering >  Trying to reverse the text file in node.js
Trying to reverse the text file in node.js

Time:10-24

I am trying to reverse the text of my file as shown below.

help.txt
Hi my name is mitchell
This is my practice midterm
cheese pizza sucks
help me please

The output should be:
help me please
cheese pizza sucks
this is my practice midterm
Hi name is mitchell

My output is:
esaelp em pleh
skcus azzip eseehc
mretdim ecitcarp ym si sihT
llehctim si eman ym iH

Here is my code

var fs = require('fs');
fs.readFile('help.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split("\n");
    for(i in array) {
        console.log(array[i]);
    }
    const reversed = array.reverse();
    console.log('reversed:', reversed);

    fs.writeFile('Output.txt', data.reverse(), (err) => {
      
    // In case of an error throw err.
    if (err) throw err;
});
});

CodePudding user response:

const txt = `Hi my name is mitchell
This is my practice midterm
cheese pizza sucks
help me please`;

// Assuming "\n" is the line delimiter
console.log(txt.split("\n").reverse());


// Assuming "\r\n" is the line delimiter
// console.log(txt.split("\r\n").reverse());

CodePudding user response:

I believe the solution you're looking for is found in the readline module.

  • This answer from @Ark-kun demonstrates well how to implement the module. As noted in that answer, the method to read a file line-by-line is not as trivial as it may first seem.

Your scenario is slightly different from the questioned linked above, but I wanted to still highlight it for reference.

The solution for your question would be:

/* Import Node Modules */
const fs = require("fs");
const readline = require("readline");

/*
* Function to process line by line.
* This example is taken from the docs and modified
* for your scenario.
*/
async function processLineByLine() {
 /* Read stream and interface */
 const inputStream = fs.createReadStream("./test.txt");
 const lineReader = readline.createInterface({
   input: inputStream,
   terminal: false,
 });

 /* Push each line to a new array. */
 const results = [];
 for await (const line of lineReader) {
   results.push(line);
 }

 /* Return a new array, reversed. */
 return results.reverse();
}

/* Do something with the result. */
processLineByLine().then(res => console.log(res));

For more information, the following may be useful:

  • Related