Raja Raja - 3 months ago 7
Node.js Question

node.js unable to access local module

I have written a small module as part of

learnyounode
. But I am unable to access it. And do I need to call funtion at module file ?

Module written as

==> filter.js <==
var fs = require('fs') , path=require('path')

dirpath_name=process.argv[2]
exthide_name="."+process.argv[3]

var filter_function=function(dirpath_name,exthide_name) {
fs.readdir(dirpath_name , function(err,list) {
if(err) console.log(err)

for( var i in list) {
if(path.extname(list[i]) == exthide_name)
console.log(list[i])
}});
}


module.exports=filter_function ;


Module used as

==> filter_use.js <==
var using = require('./filter.js')

using.filter_function(process.argv[2],process.argv[3])


Error

linuxmen@linuxmen-fresh:~/test/test1$ node filter_use.js
/home/linuxmen/test/test1/filter_use.js:3
using.filter_function(process.argv[2],process.argv[3])
^

TypeError: using.filter_function is not a function
at Object.<anonymous> (/home/linuxmen/test/test1/filter_use.js:3:7)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (bootstrap_node.js:352:7)
at startup (bootstrap_node.js:144:9)
at bootstrap_node.js:467:3
linuxmen@linuxmen-fresh:~/test/test1$


Please help.

Thank you.

Answer

There are two problems in your code.

First: your function is async, so much better provide callback to it.

var fs = require('fs'), path = require('path');

dirpath_name=process.argv[2];
exthide_name="." + process.argv[3];

var filter_function = function (dirpath_name, exthide_name, callback) {
    fs.readdir(dirpath_name , function(err,list) {
        if(err) 
            return callback(err)

        callback(null, list);
    });
});

Second: export use like below

// filter.js
module.exports = filter_function;
...
var filter = require('filter');
filter(arg1, arg2, function(err, result { ...}))

or

// filter.js
exports.filter_function = filter_function;
...
var filter = require('filter');
filter.filter_function(arg1, arg2, function(err, result { ...}))

You can simple print var to see what module exports.

var filter = require(filter);
console.log(filter);
Comments