我写了一个小模块作为learnyounode
的一部分。但我无法访问它。我需要在模块文件中调用函数吗?
模块编写为
==> 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 ;
用作
的模块==> filter_use.js <==
var using = require('./filter.js')
using.filter_function(process.argv[2],process.argv[3])
错误
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$
请帮忙。
谢谢。
答案 0 :(得分:0)
您的代码中存在两个问题。
首先:你的函数是异步的,所以更好的回调它。
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);
});
});
第二:出口使用如下
// filter.js
module.exports = filter_function;
...
var filter = require('filter');
filter(arg1, arg2, function(err, result { ...}))
或
// filter.js
exports.filter_function = filter_function;
...
var filter = require('filter');
filter.filter_function(arg1, arg2, function(err, result { ...}))
您可以简单地打印var以查看哪个模块导出。
var filter = require(filter);
console.log(filter);