Home > Back-end >  Read Lines of figures in Text file and add String to each line
Read Lines of figures in Text file and add String to each line

Time:01-21

I'm trying to read lines of figures in a text file, add a string to each 'paid' and saved all inside another text file. But I'm confused with the output I'm getting. the commented codes are for saving it in a text file.

  fs.readFile('./figures.txt', 'utf8', (err, data) => {
 
   
    const figures = data.split('\n');
    for (let i = 0; i < figures.length; i  ) {
      console.log(figures[i]   'paid' );
    }
    // fs.writeFile('./paidApproved.txt', figures.join('\n'), (err) => {
    //   if (err) {
    //     reject(err);
    //   }
      
    // });
  });

Output i got

paid50
paid44
179987paid

CodePudding user response:

Seems like the end-of-file marker is different from what you have considered in your code.

We have two end-of-file markers:

  • \n on POSIX
  • \r\n on Windows

So if you're sure about the structure of the file, and If you think the file itself has no problem, then you need to apply a tiny change in your code. Instead of explicitly putting \n as a line breaker, you need to ask os for the line breaker, and your code will be more flexible.

const os = require('os');

fs.readFile('./figures.txt', 'utf8', (err, data) => {
   const figures = data.split(os.EOL);
  // rest of code
});
  • Related