Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require in nodejs

The argument of require(...) in node.js is a filename. If I had a module source code in a string code, could I somehow call require(code) and load functions from that string?

like image 912
Cartesius00 Avatar asked Aug 23 '12 16:08

Cartesius00


People also ask

Is require is a module in NodeJS?

js require Module. Each JavaScript file is treated as a separate module in NodeJS. It uses commonJS module system : require(), exports and module.

Should I use import or require in NodeJS?

NOTE: You must note that you can't use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.

What can I use instead of require in NodeJS?

Use Import Instead of Require in Node App.

Why we use require in js?

“Require” is built-in with NodeJS require is typically used with NodeJS to read and execute CommonJS modules. These modules can be either built-in modules like http or custom-written modules. With require , you can include them in your JavaScript files and use their functions and variables.


2 Answers

I put this into a function for reuse. It creates a file in the os temp directory based on a random hash, requires it and then deletes it.

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;
}

Then you can do:

var carString = "exports.start = function(){ console.log('start'); };",
    car       = requireString(carString);

console.log("Car:", car);

This is still more of a workaround, but more convenient to use, I think.

like image 71
Thomas Fankhauser Avatar answered Oct 04 '22 02:10

Thomas Fankhauser


A work around could be to write the module source code to a temporary file ./tmp-file.js and then require('./tmp-file'), and then remove the file.

This is probably not optimal because you would either have to block and write the file synchronously, or put everything requiring that module in the callback to the async write.

A working example for async file write (gist - also includes sync file write):

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
like image 30
zackdever Avatar answered Oct 04 '22 01:10

zackdever