1

I am fairly new to NodeJS, I am trying to read all files in a given dir and then print out the results line by line using the code below

 var fs=require('fs'),fsf = require('fs'),lazy = require('lazy'); var fr; var dir = '/path/to/dir'; fs.readdir(dir,function(err,files){ if (err) throw err; files.forEach(function(file){ console.log(file); fr = fsf.createReadStream(file); //console.log(fr); new lazy(fr).lines.forEach(function(line){ console.log(line.toString()); }); }); 

I am getting the following error

Cannot call method 'toString' of undefined Any pointers will be really appreciated!

6
  • whay are you using two different kind of fs ? Commented Jul 17, 2014 at 2:59
  • Yeah sorry, that was part of the debugging to see if I get a different result. I should have removed that. Commented Jul 17, 2014 at 3:00
  • just try to write one line before console.log, if (line) see it works or not Commented Jul 17, 2014 at 3:09
  • I tried your code but I didn't get this problem, I got error ENOENT so I changed your createReadStream(file) to createReadStream(dir+'/'+file). This could also a problem. Commented Jul 17, 2014 at 3:13
  • Firstly thanks for your response. Unfortunately even after using createReadStream(dir+'/'+file) I still get the same issue console.log(line.toString()); ^ TypeError: Cannot call method 'toString' of undefined Commented Jul 17, 2014 at 3:20

1 Answer 1

1

Update: - There were actually two issues

  1. (main) The blank lines in the individual files were causing this exception.
  2. The hidden files were getting picked up by the program.

Corrected both and here is the refactored code

var fs=require('fs'),lazy = require('lazy'); var fr; var dir = '/path/to/dir'; fs.readdir(dir,function(err,files){ //Get a listing of all the files in the dir if (err) throw err; files.forEach(function(file){ if(file.search('\\.md') != -1) { //Only read markdown files console.log(file); fr = fs.createReadStream(file); new lazy(fr).lines.forEach(function(line){ if (typeof line != 'undefined'){ // Skip blank lines within the files if ((line.toString().search('\\+') != -1)||(line.toString().search('@') != -1)){ console.log(line.toString()); } } }); } }); }); 

The code seems fine and is working with other directories and on other machines. After some investigation it seems to be an issue with the .DS_Store hidden files in the directory. I was trying this on a Mac with OSX 10.9.4. I am not 100% sure, but for now that seems to be the likely cause of the error. Thanks!

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I wanted to do that, but since I answered my own question, I will need to wait for 24hrs before I can accept it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.