user1999645
user1999645

Reputation: 107

Requiring Javascript modules from both Node and Browser runtimes

I am using Nodejs for writing some sample programs, which should also be callable from a browser. I am facing an issue with calling JavaScript files from within Nodejs, in a way that would be compatible with browser JS semantics as well (so require, which is Node specific, won't do the job).

Suppose I have three .js files: "A.js", "B.js" and "C.js". "A.js" is written in Node. "B.js" and "C.js" are written in pure JavaScript (that is, they should be callable from a browser).

I need to call a function b() present in "B.js" from "A.js". So I eval() "B.js" exporting the method b(). This works properly. The problem occurs when my function b() in "B.js" calls a function c() in "C.js".

B.js:

function b()
{
    console.log('In function b');
    c();
}

C.js:

function c()
{
    console.log('In function c');
}

How do i make sure the dependancy is resolved? Any help would be appreciated. Thanks!!!

Upvotes: 2

Views: 677

Answers (2)

Spoike
Spoike

Reputation: 121772

You can load the plain vanilla javascript file manually and eval it. In your case you could create an node module that loads the pure javascript files. Like this:

bc.js:

var fs = require('fs');

// load and eval b.js and c.js
eval(fs.readFileSync('./b.js','utf8') + fs.readFileSync('./c.js','utf8'));

// put function b and c in exports
module.exports = {
    b : b,
    c : c
};

So whenever you require bc.js, you'll get both the b and c function and b can use the c function.

For further details see the following question: Load "Vanilla" Javascript Libraries into Node.js

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60767

In node.js, there is the require function, allowing you to require a file and use what's exported.

C.js:

function c() {
    console.log('In function c');
}

// This is the exported object
module.exports = {
    c: c
};

B.js:

function b() {
    var c = require('./c.js');
    // "c" is now the exported object

    console.log('In function b');
    c.c();
}

module.exports = {
    b: b
};

A.js:

var b = require('./b.js');

b.b(); // "In function b" "In function c"

You should definitely read up on how to handle modules in node.js: http://nodejs.org/api/modules.html

Upvotes: 1

Related Questions