Car*_*s00 6 javascript node.js
require(...)node.js中的参数是文件名.如果我在一个字符串中 有一个模块源代码code,我可以以某种方式调用require(code)并加载该字符串中的函数吗?
解决方法是将模块源代码写入临时文件./tmp-file.js,require('./tmp-file')然后删除该文件。
这可能不是最佳选择,因为您要么必须同步阻止并写入文件,要么将需要该模块的所有内容放在异步写入的回调中。
异步文件写入的工作示例(要点 - 还包括同步文件写入):
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/');
});
Run Code Online (Sandbox Code Playgroud)
结果是:
$ curl 127.0.0.1:1337
> Hello World
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
511 次 |
| 最近记录: |