I have a directory tmp
that has 3 test node.js modules [mod0.js, mod1.js, mod2.js]
.
I am attempting to write a function in order to import these three modules into an array and then return said array. I can drop to REPL and can import each file using var x = require("./tmp/mod0");
etc without any issue.
When I attempt to run the following function though to automate this, I receive the error [Error: Cannot fine module './tmp/mod0']
.
var _importFiles = function(path, files){
var moduleList = []
, trimmedName;
files.forEach(function (element, index, array){
if (_fs.lstatSync(path + "/" + element).isFile()){
trimmedName = element.substring(0, (element.length - 3));
moduleList.push(require("./" + path + "/" + trimmedName));
}
});
return moduleList;
};
I am passing in 'tmp'
for the path
parameter and the output of fs.readdirSync(path)
for the files
parameter.
If I check process.cwd();
within the if
block, it matches that of the REPL console.
I'm trying to figure out why it works when I manually do it in REPL but not automated.
I modified the code slightly to this:
var _fs = require('fs');
var path = process.cwd() + '/tmp'
var _importFiles = function(path, files){
var moduleList = [], trimmedName;
files.forEach(function (element, index, array){
if (_fs.lstatSync(path + "/" + element).isFile()){
trimmedName = element.substring(0, (element.length - 3));
moduleList.push(require("./" + path + "/" + trimmedName));
}
});
return moduleList;
};
var imports = _importFiles('./tmp', _fs.readdirSync(path));
console.log(imports);
Which gives me:
$ node import.js
[ 'imported mod0 automatically', 'imported mod1 automatically' ]
The mod files are simple module.exports = "imported mod(x) automatically";
So now my return list has an array. Also; Make sure your directory has read permissions (which im sure it does)