0

Created a file name big.file and stored values

const fs = require('fs');
const file = fscreateWriteStream('./big.file');

for(let i=0; i<= 2; i++) {
  file.write('1\r\n2\r\n3\r\n');
}
file.end()

I read the file and I tried to find the count of oddnumbers

const file2 = fs.readFile('./big.file','utf8', (err,lines) = {
 if(err) throw err;
 console.log(lines);
 const numbers = lines.map(Number);
 const oddNumbers = numbers.filte(n => n%2 ===1);
 console.log('odd number count:', oddNumbers.length);
});

This is my output:

C:\projects\rough>node index.js
1
2
3

C:\projects\rough\index.js:13
        const numbers = lines.map(Number);
                              ^

1 Answers1

2

lines is a string, not an array, because of that you're getting this error. String doesn't have map() method. To get an array you need to split data by \n (newline) character.

fs.readFile('./big.file', 'utf8', (err, data) = {
  if (err) throw err;
  const lines = data.split('\n');
  console.log(lines);
  const numbers = lines.map(Number);
  const oddNumbers = numbers.filter(n => n%2 ===1);
  console.log('Odd numbers count:', oddNumbers.length);
});
Ahmed Can Unbay
  • 2,694
  • 2
  • 16
  • 33
alexmac
  • 19,087
  • 7
  • 58
  • 69
  • nice, you should set this question answered for him @daneilcliff – Ahmed Can Unbay Sep 01 '17 at 17:02
  • How could I do the same thing using promises @alexmac –  Sep 01 '17 at 17:28
  • You need to _promisify_ `fs#readFile` method, it's possible to do using such libraries as `bluebird` or `Q`, or you can do _promisification_ manually, please check this answer to get more info: [https://stackoverflow.com/questions/45494127/how-to-create-promises-from-library/45494186#45494186](https://stackoverflow.com/questions/45494127/how-to-create-promises-from-library/45494186#45494186) – alexmac Sep 01 '17 at 17:31
  • const file3 = fs.readFile('./big.file', 'utf8') .then(results => { var data = fs.readFile('/.big.file') const lines = data.split('\n'); const numbers = lines.map(Number); const oddNumbers = numbers.filter(n => n%2 === 1); console.log('Odd numbers count:', oddNumbers.length); }) .catch(console.error); I tried this way,but I am sure its the wrong way for manual promisification. –  Sep 01 '17 at 17:50
  • You didn't promisification in provided code. Please create a new question, and I'll try to give an answer. And mark the current answer as accepted, if it solved your problem. – alexmac Sep 01 '17 at 17:51
  • https://stackoverflow.com/questions/46005981/node-js-promisifaction-error .I placed the question @alexmac –  Sep 01 '17 at 18:22