50

I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.

var fs = require('fs');
var files = fs.readdirSync('./application/models/');
for(var i in files) {
  var definition = require('../application/models/'+files[i]).Model;
  console.log('Model Loaded: ' + files[i]);
}

I am getting error for line number 2 . ENOENT, No such file or directory './application/models/' at Object.readdirSync (fs.js:376:18)

I have application/models on the same dir. I already checked for '/application/models/' and 'application/models/' but failed. I can see the same thing running on server.

Please help

Thanks

1
  • Have you tried process.chdir(__dirname) Commented Sep 13, 2011 at 12:06

2 Answers 2

56

If you are using relative path when calling readdirSync, make sure it is relative to process.cwd(). However, "require" should be relative to the current script.

For example, given the following structure

server.js (node process)
/lib/importer.js (the current script)
/lib/application/models/

you may need to write importer.js as:

var fs = require('fs');
var files = fs.readdirSync('./lib/application/models/');
for (var i in files) {
  var definition = require('./application/models/' + files[i]).Model;
  console.log('Model Loaded: ' + files[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

16

Have you tried the following?

var files = fs.readdirSync(__dirname+'/application/models/');

2 Comments

yes I tried the same. it also gave me the error.. No such file or directory '/home/vikas/project-admin/includes/application/models/'
Could it be because the permissions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.