Require in nodejs

The argument require(...)in node.js is the name of the file. If I had the source code of the module in a line code , can I somehow call require(code)and load functions from this line?

+5
source share
2 answers

A workaround may be to write the module source code to a temporary file ./tmp-file.js, and then require('./tmp-file'), and then delete the file.

This is probably not optimal, because you have to either lock, or write the file synchronously, or put everything that is required for this module in the callback to write async.

A working example for writing an async file ( gist - also includes recording a synchronization 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/');
});

Results in:

$ curl 127.0.0.1:1337
> Hello World
+1

. 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);

, , .

+2

All Articles