Industrial
Industrial

Reputation: 42758

Accessing globals from node.js modules?

I want to separate some functions into a file named helpers.js, in which I have put the below shown code. What should I do to access the app variable from inside my method in order to be able to fetch my config element named Path?

Helpers = {

    fs:   require('fs'),

    loadFileAsString: function(file) {
        return this.fs.readFileSync( app.set('Path') + file)+ '';
    }
}

module.exports = Helpers;

Upvotes: 2

Views: 507

Answers (1)

alessioalex
alessioalex

Reputation: 63663

So from what I see you need the app variable form Express. You can send it as a function param to loadFileAsString, for ex:

helpers.js

Helpers = {

    ...

    loadFileAsString: function(file, app) {
        return this.fs.readFileSync( app.set('Path') + file)+ '';
    }
}

module.exports = Helpers;

some_file.js

app = express.createServer();
...
helpers = require('./helpers.js');
helpers.loadfileAsString(file, app);

If you want the app to be global though you can do that also: global.app = app and you can access app everywhere without sending it as a function param.

Upvotes: 3

Related Questions