简体   繁体   English

require()中的函数引发未定义的错误

[英]Function from require() throws undefined error

As a beginner to NodeJS this might be straigtforward but yet I am unable to figure out where I am going wrong 作为NodeJS的初学者,这可能是很明智的选择,但是我无法弄清楚哪里出了问题

My home.js file is as follow 我的home.js文件如下

module.exports = function (deps) {
  var sample = require('../lib/sample'), // My own library
      express   = require('express'),
      router    = express.Router();

  router.get('/', function (req, res) {
     op = sample.parse('hi'); // Error here
     res.send(op);
  });

  return router;
 };

Under lib folder, my sample.js code is 在lib文件夹下,我的sample.js代码是

module.exports = function () {

  function parse(text) {
      return 'hello' + text;
  }

  return {
      'sample': {
          'parse': parse
      }
  };
};

But I get an error saying undefined is not a function on the highlighted line. 但是我收到一个错误消息,指出undefined is not a function突出显示行上的undefined is not a function Can anyone let me know what I am missing? 谁能让我知道我在想什么?

Since you export a function, sample will be a function now. 由于您导出了函数,因此sample现在将成为函数。 You need to explicitly execute it to get the same object. 您需要显式执行它以获得相同的对象。 So, you need to do something like this 所以,你需要做这样的事情

var sample = require('../lib/sample')().sample

Now, the require statement returns the function, and we immediately execute it, which returns an object with sample property. 现在, require语句返回该函数,我们立即执行该函数,该函数返回一个带有sample属性的对象。 Since you are interested in sample property only, we get only the sample property. 由于您仅对sample属性感兴趣,因此我们仅获取sample属性。

If you were planning to hide the implementation of parse from the users, I would suggest doing 如果您打算向用户隐藏parse的实现,建议您这样做

function parse(text) {
    return 'hello' + text;
}

module.exports = {
  'parse': parse
};

Now, you are simply exporting the parse function, in an object and the code which requires this module will be able to use parse function, like you mentioned in the question. 现在,您只需在一个对象中导出parse函数,并且需要该模块的代码将能够使用parse函数,就像您在问题中提到的那样。

Your module.exports evaluates to a function which when called yields the object containing the parse function you are trying to call, under some nesting. 您的module.exports评估为一个函数,该函数在被调用时会产生包含您尝试调用的parse函数的对象,该对象处于某种嵌套状态。 You might try restructuring your sample.js file to look like this: 您可以尝试重组sample.js文件,使其看起来像这样:

function parse(text) {
    return 'hello' + text;
}

module.exports = {
    parse: parse
};

Unless you really need the function wrapping shown in your example. 除非您确实需要示例中显示的函数包装。 In that case you'll have to unwrap it where you import it, so something like this: 在这种情况下,您必须将其解包到导入位置,所以类似以下内容:

var sample = require('../lib/sample')().sample

Change your exports to: 将您的exports更改为:

module.exports = function () {

  function parse(text) {
      return 'hello' + text;
  }

  return {
      'parse': parse
  };
};

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

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