[Noob question] importing functions from another file in node

55 views
Skip to first unread message

Ginger

unread,
Oct 11, 2015, 12:37:00 AM10/11/15
to nodejs
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.


Nanang Mahdaen El Agung

unread,
Oct 11, 2015, 12:41:41 PM10/11/15
to nodejs
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
();

 


Ryan Schmidt

unread,
Oct 11, 2015, 12:41:41 PM10/11/15
to nod...@googlegroups.com
Unlike in a web browser, every JavaScript file gets its own scope in node. That means you cannot access its contents from other files, unless you export them.

If you want to access a, b, c from your own file, you have to export them. More likely, if a, b, c are only used by those 100 functions and are not meant to be used by your own code, then you don't need to export them.


Reply all
Reply to author
Forward
0 new messages