Load and execute external file in node.js

Problem

is it easy/possible to run a node js file from another node js file? For instance, i'm having two files test1.js and test2.js. i want to execute the test1.js file from test2.js.

Problem courtesy of: sudhakar

Solution

I think the better way to accomplish what you're trying to do would be to do what my other answer suggests. But to execute commands on the command line as your questions suggests, you want to use child_process.exec. For example:

var exec = require('child_process').exec,
    child;

child = exec('node test2.js {{args}}',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});
Solution courtesy of: kentcdodds

Discussion

You simply run require('test2.js'), and then call a function on the exported object. From the documentation on modules:

Node has a simple module loading system. In Node, files and modules are in one-to-one correspondence. As an example, foo.js loads the module circle.js in the same directory.

The contents of foo.js:

var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));

The contents of circle.js:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

The module circle.js has exported the functions area() and circumference(). To export an object, add to the special exports object.

Note that exports is a reference to module.exports making it suitable for augmentation only. If you are exporting a single item such as a constructor you will want to use module.exports directly instead.

function MyConstructor (opts) {
  //...
}

// BROKEN: Does not modify exports
exports = MyConstructor;

// exports the constructor properly
module.exports = MyConstructor;

Variables local to the module will be private. In this example the variable PI is private to circle.js.

The module system is implemented in the require("module") module.

Discussion courtesy of: kentcdodds

This recipe can be found in it's original form on Stack Over Flow.