【问题标题】:NodeJS - Requiring module returns empty arrayNodeJS - 需要模块返回空数组
【发布时间】:2013-03-14 14:36:01
【问题描述】:

尽可能编写最简单的模块,我们将其写入 hello.js:

var hello = function(){
  console.log('hello');
};

exports = hello; \\ Doesn't work on Amazon EC2 Ubuntu Instance nor Windows Powershell

我运行 Node 并需要模块

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

当我应该得到[Function] 时,会返回一个空数组{}

我尝试用module.exports 替换exports,但这在我的Windows Powershell 上不起作用。它确实适用于我的 Amazon EC2 Ubuntu 实例,那么为什么 exports 不起作用? API 有变化吗?如果这些都不起作用,Powershell 可能会发生什么?

我知道 Windows 不是最理想的开发环境,但我无法理解这么简单的事故。

【问题讨论】:

  • {} 不是一个数组,它是一个对象。 [] 是一个数组。从技术上讲,[] 也是一个对象,因为Array 是从Object 扩展而来的,但无论您使用哪种方式对其进行切片,{} 都不是一个数组。

标签: node.js


【解决方案1】:

编辑

用 ES6 导出会更好一些

export const hello = function(){
  console.log('hello');
};

导入看起来像

import {hello} from './file';

原答案

你会想要使用module.exports

var hello = function(){
  console.log('hello');
};

module.exports = hello;

如果只是导出一件事,我通常会在一行中完成所有操作

var hello = module.exports = function() {
  console.log('hello');
};

附加功能

如果您使用命名函数,如果您的代码出现错误,您的堆栈跟踪看起来会好很多。这是会这样写

// use a named function               ↓
var hello = module.exports = function hello() {
  console.log("hello");
};

现在堆栈跟踪中的函数名不再显示anonymous,而是显示hello。这使得查找错误变得更加容易。

我在任何地方都使用这种模式,以便我可以轻松地调试代码。这是另一个例子

// event listeners          ↓
mystream.on("end", function onEnd() {
  console.log("mystream ended");
};

// callbacks                              ↓
Pokemon.where({name: "Metapod"}, function pokemonWhere(err, result) {
  // do stuff
});

如果要导出多个东西,可以直接使用exports,但必须提供key

// lib/foobar.js
exports.foo = function foo() {
  console.log("hello foo!");
};

exports.bar = function bar() {
  console.log("hello bar!");
};

现在当你使用那个文件时

var foobar = require("./lib/foobar");

foobar.foo(); // hello foo!
foobar.bar(); // hello bar!

作为最后的奖励,我将向您展示如何通过导出单个对象来重写 foobar.js,但仍然获得相同的行为

// lib/foobar.js
module.exports = {
  foo: function foo() {
    console.log("hello foo!");
  },
  bar: function bar() {
    console.log("hello bar!");
  }
};

// works the same as before!

这允许您以最适合该特定模块的任何方式编写模块。耶!

【讨论】:

    【解决方案2】:

    exports 不起作用的原因是引用冲突。每个文件中的顶部变量是module,它有一个属性module.exports。加载模块时,会在后台创建新变量。会发生这样的事情:

    var exports = module.exports;
    

    显然exports 是对module.exports 的引用,但是这样做

    exports = function(){};
    

    强制exports 变量指向函数对象——它不会改变module.exports。这就像在做:

    var TEST = { foo: 1 };
    var foo = TEST.foo;
    foo = "bar";
    console.log(TEST.foo);
    // 1
    

    常见的做法是:

    module.exports = exports = function() { ... };
    

    我不知道为什么它在 Windows Powershell 下不起作用。老实说,我什至不确定那是什么。 :) 你不能只使用本机命令提示符吗?

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 2021-02-14
      • 2019-02-23
      • 2021-09-17
      • 2020-05-19
      • 2021-11-18
      • 1970-01-01
      • 2020-12-29
      • 2016-05-29
      相关资源
      最近更新 更多