如何导出节点模块? [英] How do I exports node modules ?

查看:115
本文介绍了如何导出节点模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用回调读取目录和导出文件名,但是当我导入readDirectory函数时我的模块没有发送数据,不知道下面的代码出了什么问题?我的回调函数返回模块本身的值,但是在使用导出时它不会发送。



我尝试过:



main.js



var fs = require('fs');

var path =' ./Logs';

函数readDirectory(){

fs.readdir(路径,函数(错误,项目){

返回filesData(项目);

});

}

函数filesData(项目){

var data = JSON。 stringify(items)

console.log('来自模块的数据',数据);

返回数据;





}

exports.readDirectory = readDirectory;



app.js



var readDirectory = require('./ main');

var obj = readDirectory.readDirectory();



console.log(JSON.stringify(obj));

解决方案

尝试执行以下代码:





direc toryOps.js

(function(directoryOps){

var fs = require('fs');
var path ='。/ Logs';

函数filesData(items){
var data = JSON.stringify(items)
console.log('来自模块的数据',数据);
返回数据;
}

directoryOps.readDirectory = function(){
fs.readdir(path,function(err,items){
return filesData(items);
});
};

})(module.exports);





App.js

 var directoryOps = require('./ directoryOps'); 
var obj = directoryOps.readDirectory();





对于我在文件名中所做的更改,我们深表歉意。



**注意:

还有你当前创建的方式main。 js,它会将诸如fs,path,filesData,readDirectory之类的变量添加到全局范围,从而污染它。因此,最好将该函数作为IIFE(匿名函数)的一部分来执行。这不会给全局范围增加变量,保持你的范围清洁。



希望它有帮助......

搜索结果


I am reading directory and exporting file names using callbacks but my module is not sending data when i import readDirectory function, Any idea what is going wrong with below code ? my callback return values in module itself but its not sending while using exports.

What I have tried:

main.js

var fs = require('fs');
var path = './Logs';
function readDirectory() {
fs.readdir(path, function(err,items) {
return filesData(items);
});
}
function filesData(items) {
var data = JSON.stringify(items)
console.log('data from module',data);
return data;


}
exports.readDirectory = readDirectory;

app.js

var readDirectory = require('./main');
var obj = readDirectory.readDirectory();

console.log(JSON.stringify(obj));

解决方案

Try executing the following code:


directoryOps.js

(function(directoryOps) {

  var fs = require('fs');
  var path = './Logs';

  function filesData(items) {
    var data = JSON.stringify(items)
    console.log('data from module',data);
    return data;
  }

  directoryOps.readDirectory = function() {
    fs.readdir(path, function(err,items) {
      return filesData(items);
    });
  };

})(module.exports);



App.js

var directoryOps = require('./directoryOps');
var obj = directoryOps.readDirectory();



Sorry for the changes I made in the file name.

**Note:

Also the way you are currently creating "main.js", it would add variables like "fs, path, filesData, readDirectory" to the global scope and hence polluting it . So its better to execute the function as a part of IIFE (anonymous function). This would not add variable to the global scope, keeping your scope clean.

Hope it helps...




这篇关于如何导出节点模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆