简体   繁体   中英

Javascript — exports in Node.js vs browser

I'm attempting to run this short program from Eloquent Javascript in the section on Modules.

var weekDay = function() {}();

(function(exports) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday"];

  exports.name = function(number) {
    return names[number];
  };
  exports.number = function(name) {
    return names.indexOf(name);
  };
})(this.weekDay = {});

console.log(weekDay.name(weekDay.number("Saturday")));

The proper output should be // -> Saturday .

It works perfectly in the browser. However, when I try to run it in the Node interpreter, I get this error:

TypeError: Cannot read property 'name' of undefined

I can only assume it has something to do with the way Node handles the exports keyword. Can somebody help me gain at least a rough understanding of this behavior?

The answer of Nir Levy is correct, but I posted this answer as well, because you were talking about Modules. This is how you make a module of your piece of code.

//create your module like this and put this module in a separate file (ex. weekDay.js)
var weekDay = (function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

  var name = function(number) {
    return names[number];
  };
  var number = function(name) {
    return names.indexOf(name);
  };

  return {
    number: number,
    name: name
  } 
})(); //it's a self executing function

//exporte module
module.exports = weekDay



//to get your module (in another file)
var weekDayModule = require('./weekDay'); //path to module

console.log(weekDayModule.name(weekDayModule.number('Saturday')));

in node.js this line:

var weekDay = function() {}();

just generates an undefined variable weekDay, since all it does is define a function with en empty body (the {} in your code) and run it right away. Since the body is empty (and most importantly, no return statement), it yields undefined

The way to do what you want is put the entire definition inside this function, and define what to expose, like this:

var weekDay = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday"];

  var name = function(number) {
    return names[number];
  };
  var number = function(name) {
    return names.indexOf(name);
  };

  return {
    number: number,
    name: name
  }

}();


console.log(weekDay.name(weekDay.number("Saturday")));

Change first line to var weekDay = {}; and when you invoke your iife then just put into it weekDay what you have created in the first line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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