hussain
hussain

Reputation: 7123

How to get files list using fileSystem?

I am trying to get list of files in specified directory but its throwing error any idea what is implemented wrong in below code.

service.js

var fs = require('fs');
var path = require('path');
var async = require('async');
var filePath = path.resolve('./logs/dit/');

  function checkSearchObj ()  {
       fs.readdir(filePath,function (err, files) {
         files.forEach(function(file) {
           console.log(file);
         });
       })
    }

    checkSearchObj();

error

TypeError: Cannot read property 'forEach' of undefined
    at C:\Users\sh529u\WebstormProjects\ulog\app\serverf
s:8:15
    at FSReqWrap.oncomplete (fs.js:82:15)

Upvotes: 0

Views: 138

Answers (1)

rsp
rsp

Reputation: 111486

Change this:

function checkSearchObj ()  {
   fs.readdir(filePath,function (err, files) {
     files.forEach(function(file) {
       console.log(file);
     });
   })
}

to this:

function checkSearchObj ()  {
   fs.readdir(filePath,function (err, files) {
     if (err) {
       console.log('Error:', err);
       return;
     }
     files.forEach(function(file) {
       console.log(file);
     });
   })
}

to see what's the error.

You need to check for errors instead of assuming that there was no error or otherwise you will try to access undefined variables and the only error you'll see is that you access undefined and not the actual error that's in err in this case.

Your callback will either get the err or the files but not both.

Update:

After changing the code to display error you got:

Error: { [Error: ENOENT: no such file or directory, scandir 'C:\Users\Web stormProjects\ulog\app\serverfiles\logs\dit'] errno: -4058, code: 'ENOENT', syscall: 'scandir', path: 'C:\\Users\\sh529u\\WebstormProjects\\ulog\\app\\serverfiles‌​\\logs\\dit'

Which means that the program doesn't display the files in the directory because there is no such directory. Mystery solved. Now you can see how useful it is to actually check the errors.

Upvotes: 3

Related Questions