NodeJS – 要求模块返回空数组
编写最简单的模块,我们可以写入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
replaceexports
,但是这不适用于我的Windows Powershell。 它在我的Amazon EC2 Ubuntu实例上工作,那么为什么不exports
工作? API是否改变了? 而Powershell可能会发生什么,这些都没有工作?
我知道Windows并不是最理想的开发环境,但我无法摆脱这种简单的不幸。
exports
不工作的原因是因为参考冲突。 每个文件中的顶层variables是具有属性module.exports
module
。 当模块被加载时,在后台创build新的variables 。 像这样的事情发生:
var exports = module.exports;
很明显, exports
是对module.exports
的引用,但是在做
exports = function(){};
强制exports
variables指向函数对象 – 它不会改变module.exports
。 这就像在做:
var TEST = { foo: 1 }; var foo = TEST.foo; foo = "bar"; console.log(TEST.foo); // 1
通常的做法是做:
module.exports = exports = function() { ... };
我不知道为什么它不能在Windows Powershell下工作。 说实话,我甚至不知道那是什么。 :)你不能只使用本机命令提示符?
编辑
使用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'); };
附加function
如果你使用了一个命名的函数 ,如果你的代码发生了错误,你的堆栈跟踪将会看起来好多了。 这是我写这个的方式
// use a named function ↓ var hello = module.exports = function hello() { console.log("hello"); };
现在,不是在堆栈跟踪中显示anonymous
函数名称,而是显示hello
。 这使得查找错误变得容易多了。
我到处使用这个模式,以便我可以轻松地debugging代码。 这是另一个例子
// 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!
这使您可以以最适合该特定模块的方式编写模块 。 好极了!