0

I am very new to javascript, and I want to read lines of strings into let's say an array, I used this:

  const fs = require('fs');

let words = [];

fs.readFile('C:\\Users\\lenovo\\Desktop\\words.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  words.push(data);
  console.log(words);
});

and it works, BUT, the output is formatted like this:

'wrong\r\n' +
    'year\r\n' +
    'yellow\r\n' +
    'yes\r\n' +
    'yesterday\r\n' +
    'you\r\n' +
    'young\r\n' +
    'Bernhard\r\n' +
    'Breytenbach\r\n' +

is there a way to fix this?

ehady
  • 3
  • 1
  • depends - what is wrong with it? you push a single value to an array, you'll get a single value out of an array – Jaromanda X Aug 05 '22 at 09:28
  • Seems like you want to read your file into an array line by line. So, does this answer your question? [node.js: read a text file into an array. (Each line an item in the array.)](https://stackoverflow.com/questions/6831918/node-js-read-a-text-file-into-an-array-each-line-an-item-in-the-array) – derpirscher Aug 05 '22 at 09:30

1 Answers1

0

You could do words = data.split("\r\n"). This will split your file into lines and saves it into the words array.

But keep in mind, that Unix like systems uses different line endings (\n) than Windows (\r\n).

PiFanatic
  • 233
  • 1
  • 4
  • 14