Skip to content

Defining lme globally

Vajahath Ahmed edited this page Mar 3, 2017 · 6 revisions

🦀 Not officially recommended.

Why should I care about this?

Normally, if you want to use lme in a file, you have to first require it in the top of the same file.

const lme = require('lme');
...

But we don't have to require(console); to use console.log in any file. To get a similar experience with lme, you can define it globally. (am I polluting the namespace?)

How?

Define lme by requireing it at the top of the very first file in which node starts execution. For example, to start my application, I use the following command.

$ node server.js

Then my server.js file goes like this (Note: should not use var/ let/ const to define it. Simply require it):

lme = require('lme');

By doing this, we're exposing lme to the global namespace. So it will be available to every file afterwards inside the application.

Example

greet.js

function greet(name){
    lme.s("hi " + name + "!");    
}

module.exports = greet;

app.js

// globally define lme
lme = require('lme');

// get greet function
const greet = require('./greet');

let name = "Divya"
greet(name);

and run

$ node app.js

Am I polluting the namespace?

Strictly speaking, you are polluting the global namespace. But it can also be seen in a way that you are harnessing a JavaScript feature.

Clone this wiki locally