0

I'm trying to count the number of lines in a text file using Node.js and set that number to a variable. I found a solution here, but I get this error when trying to use the code.

fs.js:540
  binding.open(pathModule._makeLong(path),
          ^

TypeError: path must be a string
    at TypeError (native)
    at Object.fs.open (fs.js:540:11)
    at ReadStream.open (fs.js:1673:6)
    at new ReadStream (fs.js:1660:10)
    at Object.fs.createReadStream (fs.js:1608:10)
    at Object.<anonymous> (C:\Users\Aidan\Desktop\Javascript\test.js:3:15)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

To my understanding, this is saying that there is an error with the fs module itself. This couldn't possibly be right. Maybe the enviornment I'm running Node.JS in is not allowing this code to properly execute? I'm running Windows 10 64bit, by the way. A fixed version of this code or an entirely new solution will work. Thank you so much!

Community
  • 1
  • 1
Toxxic
  • 57
  • 1
  • 1
  • 6

1 Answers1

0

Your file is an array, so you have to refer to it through myFile[0]. Also, check that you are running the most recent version of node ( 6.x)

Even Stensberg
  • 488
  • 5
  • 17
  • why need to run node 6.x? – Alex Jun 25 '16 at 18:00
  • Some features are changed in node 6, so perhaps they have changed it from v4 => v6 :) Here's the [changelog](https://nodejs.org/en/blog/release/v6.0.0/) – Even Stensberg Jun 25 '16 at 18:01
  • I'm now using the latest version of node, but I still get the error. This time, instead of saying path must be a string, it says path must be a string or a buffer. Also, where would I refer to my file? I'm decent with node but I'm also pretty new. – Toxxic Jun 25 '16 at 18:08
  • change your method calls with the new v6 methods, should be in the link I provided :) – Even Stensberg Jun 25 '16 at 18:14
  • Ok. It seems to be working now, except when I put my file path in here: require('fs').createReadStream("./file.txt"[2]), It tries to read a file named f, not file.txt. If I rename the file to f with no file extension, it works fine. – Toxxic Jun 25 '16 at 18:23
  • use import as from es6, node v6 lets you do that :) – Even Stensberg Jun 25 '16 at 18:58
  • @Even Andre Stensbergcheck https://stackoverflow.com/questions/12453057/node-js-count-the-number-of-lines-in-a-file?lq=1 – Alex Jun 25 '16 at 19:00