Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding external javascript files on node.js

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");
}
like image 295
Masiar Avatar asked Dec 14 '11 16:12

Masiar


People also ask

How do I connect an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How run external JavaScript file in HTML using node JS?

To load and execute external JavaScript file in Node. js with access to local variables, we can use the vm module. const vm = require("vm"); const fs = require("fs"); const data = fs. readFileSync("./externalfile.

How do I include another file in node JS?

To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.


1 Answers

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");
}
like image 117
DHamrick Avatar answered Oct 06 '22 00:10

DHamrick