-1

before, i already search the question asked in SOF before i deciding to ask, like here or here

but none of it solve my problem.. ok so heres my code :

const file = './PAGE1.txt';
const fs = require('fs');


fs.readFile(file,'utf-8', (e,d)=>{
let textByLine = d.split('\n'); //make it an array
let hasil=textByLine[2];
});

the page1.txt is like

Aa
Ab
Ac

so then i try

console.log(hasil)

it succeeded showing "Ac" on the console. but when i do

console.log(hasil + " Test")

it shows up "Test"

why its not "Ac Test" ?

thank you for your help.

Edit : this is solved, i just simply add '\r' :

let textByLine = d.split('\r\n'); //make it an array

and now the console show "Ac Test".

now i wanna ask what does this "\r" function?

why i need it to solve my question..

thankyou again :)

Community
  • 1
  • 1
SADmiral
  • 41
  • 4

2 Answers2

0
const fs = require('fs'); // file system package
const rl = require('readline'); // readline package helps reading data line by line
// create an interface to read the file
const rI = rl.createInterface({
  input: fs.createReadStream('/path/to/file') // your path to file
});
rI.on('line', line => {
  console.log(line); // your line
});

You can simply use this to log line by line data. But in real world you will use with Promise e.g

const getFileContent = path =>
  new Promise((resolve, reject) => {
    const lines = [],
      input = fs.createReadStream(path);

    // handle if cann't create a read strem e.g if file not found
    input.on('error', e => {
      reject(e);
    });

    // create a readline interface so that we can read line by line
    const rI = rl.createInterface({
      input
    });

    // listen to event line when a line is read
    rI.on('line', line => {
      lines.push(line);
    })
      // if file read done
      .on('close', () => {
        resolve(lines);
      })
      // if any errors occur while reading line
      .on('error', e => {
        reject(e);
      });
  });

and you will use it like this.

getFileContent('YOUR_PATH_TO_FILE')
  .then(lines => {
    console.log(lines);
  })
  .catch(e => {
    console.log(e);
  });

Hope this will help you :)

ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58
0

Edit : this is solved, i just simply add '\r' :

let textByLine = d.split('\r\n'); //make it an array

and now the console show "Ac Test"

now i wanna ask what does this "\r" function?

why i need it to solve my question..

thankyou again :)

SADmiral
  • 41
  • 4