Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving files from Directory Node Js

Tags:

node.js

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

like image 720
Sharmaji Avatar asked Sep 13 '11 11:09

Sharmaji


People also ask

How do I read a directory in node JS?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.

How do you read all files from a folder in JS?

To read all files in a directory, store them in objects, and send the object with Node. js, we can use the readdir and readFile methods. const fs = require('fs'); fs. readdir(dirname, (err, filenames) => { if (err) { onError(err); return; } filenames.


1 Answers

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]); } 
like image 119
ivan loire Avatar answered Sep 27 '22 21:09

ivan loire