You need to export everything that you need to share or access from another 
file. So, you need to export those functions. Also, if you need to access 
those variables from other file, you need to export them as well. But if 
you only need those variables is accessible by those functions, you only 
need to export those functions.

*Example:*

*source.js*
var a = 1;
var b = 2;
var c = 3;

function abc() {}
function cba() {}

module.exports = {
  a: a,
  b: b,
  c: c,
  abc: abc,
  cba: cba
}



*main.js*

var src = require('./source.js');

console.log(src.a);
console.log(src.b);

src.abc();
src.bca();

 


If you really need to makes them available to you without exporting each 
variables and functions, you can use VM and run the source script in the 
current context. But be careful with this way.

*Example:*
var fs = require('fs');
var vm = require('vm');

// Read the script content.
var srcScript = fs.readFileSync('./source.js', 'utf8');

// Run the script content on current context.
vm.runInThisContext(srcScript);

console.log(a);
console.log(b);

abc();
cba();

 



On Sunday, October 11, 2015 at 11:37:00 AM UTC+7, Ginger wrote:
>
> Hi All,
>
> Here I have a very newbie question here about how to invoke the functions 
> been defined in external js files.
>
> Assume here I have downloaded a js file has 100 functions and lots of 
> global variables simply looks like:
>
> abc.js
> var a = 1;
> var b = 2;
> var c = 3;
> ...
>
> function abc(x){...}
> function cba(y){...}
>
> .....
> .....
>
>
> So now in my main.js file, I simply want to make a call to functions looks 
> like:
> ....
>
> var v1 = abc(x);
> var v2 = abc(y);
>
> ....
>
> then I got an error about abc is not defined. That makes sense, so I guess 
> I have to include the file or import functions in some way. I have seen 
> some solution about export each function in abc.js, but there just too many 
> of them. Also, if I have exported function abc, do I have to export those 
> variables, a, b, c? I am so confused here. @_@
>
> Thanks in advance.
>
>
>

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to nodejs+unsubscr...@googlegroups.com.
To post to this group, send email to nodejs@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/bc8659f1-c657-4b18-b292-9ef3845584d3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to