简体   繁体   English

使用module.exports返回对象

[英]Using module.exports to return an object

I'm using csvtojson to parse a csv file and want to use it in another module in NodeJS. 我正在使用csvtojson解析csv文件,并想在NodeJS的另一个模块中使用它。 Pretty sure this is a noob issue in my attempt to learn NodeJS. 可以肯定,这是我尝试学习NodeJS时遇到的一个菜鸟问题。

function loadPortfolio (portfolio) {
  //Converter Class 
  var Converter = require("./node_modules/csvtojson").Converter;
  var converter = new Converter({});

  //end_parsed will be emitted once parsing finished 
  converter.on("end_parsed", function (jsonArray) {
    var jsonText = JSON.stringify(jsonArray);
    var portfolioObj = JSON.parse(jsonText);

    module.exports = loadPortfolio;
  });

  //read from file 
  require("fs").createReadStream("./charlesriverexport.csv").pipe(converter);

};

Then in my app.js file: 然后在我的app.js文件中:

var loadPortfolio = require('./loadPortfolio');

console.log("Portfolio: ", portfolio);

But, unfortunately the portfolio object comes as undefined. 但是,不幸的是,投资组合对象是未定义的。

Any ideas? 有任何想法吗?

Thanks 谢谢

You're not calling the loadPortfolio() function anywhere, you're using the wrong variable name in your app.js file and your module.exports can be moved to improve readability 您没有在任何地方调用loadPortfolio()函数,在app.js文件和module.exports使用了错误的变量名,可以移动module.exports以提高可读性

The last part is optional but makes it easy to see whats exported at the top of every file as soon as you open it 最后一部分是可选的,但是使您很容易在打开文件后立即查看每个文件顶部导出的内容

NOTE: This only works if you use named function definitions: function myFunc() {} and NOT when you store the function in a variable ie let myFunc = function() {} . 注意:仅当使用命名函数定义时,此方法才有效: function myFunc() {}而在将函数存储在变量中时let myFunc = function() {}let myFunc = function() {}

Hoisting in JS allows to do this in your module file: 使用JS提升可以在您的模块文件中执行此操作:

module.exports = loadPortfolio;
function loadPortfolio (portfolio) {
  //Converter Class 
  var Converter = require("./node_modules/csvtojson").Converter;
  var converter = new Converter({});

  //end_parsed will be emitted once parsing finished 
  converter.on("end_parsed", function (jsonArray) {
    var jsonText = JSON.stringify(jsonArray);
    var portfolioObj = JSON.parse(jsonText);


  });

  //read from file 
  require("fs").createReadStream("./charlesriverexport.csv").pipe(converter);

};

As functions get loaded before the module is executed, you can export before the function is defined. 由于函数是在执行模块之前加载的,因此可以在定义函数之前导出。

then you need to call the function in app.js 那么您需要在app.js中调用该函数

var loadPortfolio = require('./loadPortfolio');
var portfolio = loadPortfolio();

console.log("Portfolio: ", portfolio);

Your exported module has to be a function that takes a callback as its parameter. 您导出的模块必须是一个以回调为参数的函数。 The exported function will supply the callback with the data that is generated asynchronously. 导出的函数将为回调提供异步生成的数据。

var fs = require('fs');
var Converter = require('./node_modules/csvtojson').Converter;

module.exports = function loadPortfolio (callback) {

  var converter = new Converter({});

  fs.createReadStream('./charlesriverexport.csv').pipe(converter);

  converter.on('end_parsed', function (jsonArray) {
    var jsonText = JSON.stringify(jsonArray);
    var portfolioObj = JSON.parse(jsonText);
    callback(portfolioObj);
  });

};

And in the file where you use this module: 在使用此模块的文件中:

var loadPortfolio = require('./loadPortfolio');
loadPortfolio(function(portfolioObj) {
  console.log(typeof portfolioObj); // => 'object'
});

Edit: if you want to use the asynchronously fetched portfolioObj outside of the callback context of loadPortfolio you have to set an undefined variable then assign it within the callback. 编辑:如果你想使用异步获取portfolioObj的回调上下文之外loadPortfolio你必须设置一个未定义的变量,然后在回调中进行分配。

//set undefined variable
var portfolio;

//import your function
require('./loadPortfolio')(function(portfolioObj) {

  //assign the global variable a value
  portfolio = portfolioObj;

  //when doSomething runs portfolio is guaranteed to be defined
  doSomething();
});

//see the problem with calling doSomething outside the callback?
doSomething(); // => 'undefined'

function doSomething() {
  console.log(typeof portfolio); // => 'object'
}

A neater way to do this is with promises, however. 但是,更简洁的方法是承诺。

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

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