K3rn3l5
K3rn3l5

Reputation: 361

NodeJS Reading all files in a dir by each line

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!

Upvotes: 1

Views: 1344

Answers (1)

K3rn3l5
K3rn3l5

Reputation: 361

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!

Upvotes: 1

Related Questions