Require in nodejs
Require in nodejs
node.js中require(...)
的参数是一个文件名。如果我在字符串code
中有一个模块源代码,我能以某种方式调用require(code)
并从该字符串加载函数吗?
我将其放入一个函数中以供重用。它根据随机散列在os-temp目录中创建一个文件,需要它,然后删除它
var fs = require('fs'),
os = require('os'),
crypto = require('crypto');
function requireString(moduleString) {
var token = crypto.randomBytes(20).toString('hex'),
filename = os.tmpdir() + '/' + token + '.js',
requiredModule = false;
// write, require, delete
fs.writeFileSync(filename, moduleString);
requiredModule = require(filename);
fs.unlinkSync(filename);
return requiredModule;
}
然后你可以做:
var carString = "exports.start = function(){ console.log('start'); };",
car = requireString(carString);
console.log("Car:", car);
这仍然是一种变通方法,但我认为使用起来更方便。
解决方法可以是将模块源代码写入临时文件./tmp-file.js
,然后写入require('./tmp-file')
,然后删除该文件。
这可能不是最佳的,因为您要么必须同步地阻止和写入文件,要么将需要该模块的所有内容都放在异步写入的回调中。
异步文件写入的一个工作示例(gist-也包括同步文件写入):
var http = require('http');
var fs = require('fs');
var helloModuleString = "exports.world = function() { return 'Hello World''n'; }";
fs.writeFile('./hello.js', helloModuleString, function (err) {
if (err) return console.log(err);
var hello = require('./hello');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(hello.world());
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
});
结果:
$ curl 127.0.0.1:1337
> Hello World
相关文章:
- Require in nodejs
- ReadFile in Base64 Nodejs
- What is the reason for cloning the listeners array in nodejs
- Schema.pre in Mongoose modules (NodeJS)
- linkify urls in templates-nodejs
- NodeJS put array in MongoDB doc.validate 不是一个函数
- setTimeout in nodejs - for loops
- 无法在 nodeJS:TypeError 中对用户进行身份验证:无法使用“in”运算符在 fs 中搜索“用户名”
- setInterval in nodejs
- setTimeout in nodejs
- removeListener in the Listener in nodejs
- Stream in NodeJS
- RabbitMQ no ack in nodejs
- NodeJS MSSQL WHERE IN准备的SQL语句
- res.send vs res.locals in nodejs
- cURL post request in Nodejs.
- Adding in Javascript (NodeJS)
- Github Post-Receive Hook in Nodejs
- DRY in Nodejs Express
- Faye Websocket in NodeJS