6

I have a node server and I want to add an external .js file (say something.js). I have this code for now:

var st = require('./js/something');

Where something.js is the JavaScript file inside a /js/ folder. The server compiles and run, but when I try to use functions defined in something.js node tells me they are not defined.

I also tried to run them using like st.s() but nothing happens and I have an error saying that the object has no method s().

Can anyone help me?

Thanks,

EDIT:

logging st gives {} (I obtain it from console.log(JSON.stringify(st)). Also doing console.log(st) gives {} as result.

The content of something.js is just a bunch of functions defined like this

function s() {
    alert("s");
}

function t() {
    alert("t");
}
5
  • Can you paste the something.js code here? Commented Dec 14, 2011 at 16:56
  • Use exports: stackoverflow.com/questions/5939423/… Commented Dec 14, 2011 at 16:58
  • You don't need to convert it to JSON. Just do console.dir( st );... Commented Dec 14, 2011 at 17:01
  • Racar can you please be more specific about exports? I didn't get from that question how to use them, or how should I use them in this case. Commented Dec 14, 2011 at 17:04
  • 1
    in your something.js file, do " module.exports = { st: function() { console.log('test'); } } ". Commented Dec 14, 2011 at 17:22

1 Answer 1

10

Node.js uses the CommonJS module format. Essentially values that are attached to the exports object are available to users of the module. So if you are using a module like this

var st = require('./js/something');
st.s();
st.t();

Your module has to export those functions. So you need to attach them to the exports object.

exports.s = function () {
    console.log("s");
}

exports.t = function () {
    console.log("t");
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would you import a script from an external URL (for example, javascript-modules.googlecode.com/svn/functionChecker.js)? Using require("http://javascript-modules.googlecode.com/svn/functionChecker.js"); doesn't seem to work.

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.