如何在Node.js中包含一个不是模块的文件(来创build它的一个模块)?
目的 :从一个普通的旧JavaScript文件中创build一个Node.js模块或一个Requirejs AMD模块,如下所示:
var foo = function () {};
我没有控制,我不能编辑 foo.js
为什么foo
是第一个内部的空白对象? 如何在模块中“包含”一个普通的JavaScript文件? 文件mymodule.js
:
(function(root) { if(typeof exports === 'object') { // Node.js var foo = require('./foo'); console.log(foo); // { } } else if (typeof define === 'function' && define.amd) { // RequireJS AMD define(['foo'], function () { return foo; }); } }());
加载了require
节点模块必须使用模块想要公开的所有东西来填充一个exports
对象。 在你的情况下,当你需要这个文件时,没有东西被添加到exports
,因此它显示为空。 所以简单的答案是你需要修改foo.js
的内容。 如果你不能手动执行,那么你需要以编程方式进行。 你为什么不能控制它?
最简单的方式是,如果foo.js
中的foo.js
需要使其成为合适的模块, foo.js
编程方式封装内容。
// Add an 'exports' line to the end of the module before loading it. var originalFoo = fs.readFileSync('./foo.js', 'utf8'); fs.writeFileSync('./foo-module.js', originalFoo + "\nexports.foo = foo;"); var foo = require('./foo-module.js');
你可以尝试:
var fs = require('fs'); var foo = fs.readFileSync('foo.js', 'utf8') // Or request it somehow, just get it as a string foo += "module.exports.foo = module.exports = foo;"; fs.writeFileSync('fooModule.js',foo); var foo = require('./fooModule'); // foo() and foo.foo() are both the same
注意:这需要节点。