Dougyfresh
Dougyfresh

Reputation: 616

In a Node app with express JS, how can I include and run a separate JS file?

I have a javascript file that contains some functions that grab an RSS feed and save the contents in a database. I originally had it being called by the HTML page, but I want this file to instead be running in the back-end all the time (grabbing updates from the RSS feed and saving it to a database).

My question is, how can I attach and run this separate javascript within my app? I assume it will look like this:

In app.js:

var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.SomeFunction();

This isn't working though. Also, would variables declared in my app.js be available in RSSReader.js?

Thanks.

Upvotes: 0

Views: 2137

Answers (1)

jfriend00
jfriend00

Reputation: 707158

how can I attach and run this separate javascript within my app?

The app.js code you show should work just fine. The key is that you have to make your RSSReader.js file into a module that exports the functions it wants to be public:

So, inside of RSSReader.js, you would have something like this:

module.exports = {
    someFunction: function() {
        // code here
    },
    someOtherFunction: function() {
        // code here
    }
};

Then, in your other file, you can load that module and use it like you had:

var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.someFunction();
RssReader.someOtherFunction();

node.js documentation for modules is here.

Also, would variables declared in my app.js be available in RSSReader.js?

No, they would not unless you explicitly declared the app.js variables as properties on the global object. The usual node.js convention for sharing from app.js to another module is that you create an initializer method for the RSSReader.js module (you can call it init) and you pass it any context it needs (usually an object with some properties on it) from app.js and the RSSReader.js module can then store that context for its use.

So, if you want to share some variables from app.js to RSSReader.js, you could share them via a .init() method like this:

RSSReader.js

var data;
module.exports = {
    init: function(options) {
        data = options;
    },
    someFunction: function() {
        // code here can access the data variable
    },
    someOtherFunction: function() {
        // code here can access the data variable
    }
};

app.js

var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.init({express: express, db: db});
RSSReader.someFunction();
RssReader.someOtherFunction();

Upvotes: 1

Related Questions