0

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

thank you! I attempted to upvote this answer but do not have enough reputation for it to display :(. But thank you! @Nick
@Ryan Happy I was able to help! You can mark this answer as correct (I believe there is a certain amount of time you need to wait before you can do so, though)
Ah! You're right, I marked it correct. Didn't see that checkmark there. (Sorry, major stackoverflow newb).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.