简体   繁体   English

node.js无法访问本地模块

[英]node.js unable to access local module

I have written a small module as part of learnyounode . 我已经编写了一个小模块作为learnyounode一部分。 But I am unable to access it. 但是我无法访问它。 And do I need to call funtion at module file ? 我需要在模块文件中调用funtion吗?

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. 谢谢。

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来查看导出的模块。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM