Ryan Ryan - 1 month ago 7
Javascript Question

Writing a script file to test a function? (Node.js)

I'm currently working on a program where I have a function that runs and does a bunch of things. I wrote a script over the summer at work that could take dummy input and pass it to a function call and then all I had to do was open a command prompt and say

node test.js
.

Unfortunately I don't remember what that code looked like exactly but I know it was fairly simple.

For simplicity's sake, lets say I have a function:

var double_num = function(num){
return num*2;
}


contained in a file called double.js

and I also have a blank javascript file test.js. How complicated is it to call
double_num
from test.js with something in the file like:

var result = double_num(5);
console.log(result);


from the command line using
node test.js
?

Answer

You would need to export double.js as a module, and then import that module into test.js. Should look something like this:

// double.js

var double_num = function(num){
    return num*2;
}

// export your `double_num` function as a module so 
// we can import this elsewhere in our programs
modules.export = double_num;

And in test.js make sure to include double.js by using its relative path to test.js. Assuming that they're in the same directory, it might look something like this:

// test.js

// Import `double_num` from the file we just exported it from
var double_num = require('./double_num');

var result = double_num(5);
console.log(result);