Import functions from module to global namespace in Coffeescript? - node.js

Start with your module, utils.coffee:
exports.foo = ->
exports.bar = ->
Then your main file:
utils = require './utils'
utils.foo()
foo() and bar() are functions you'll be calling frequently, so you:
foo = require('./utils').foo
bar = require('./utils').bar
foo()
This approach works when only a few functions are defined in the module, but becomes messy as the number of functions increases. Is there a way to add all of a module's functions to your app's namespace?

Use extend (with underscore or any other library that provides it. Write it yourself if necessary):
_(global).extend(require('./utils'))

If you don't want to use underscore, you could simply do:
var utils = require('./utils')
for (var key in utils)
global[key] = utils[key]

Is there a way to add all of a module's functions to your app's namespace?
No. This is, to my knowledge, the best you can do (using CS' destructuring assignment):
{foo, bar, baz} = require('./utils')

Another way to exports all modules function to global scope like so:
Application Module:
(()->
Application = #Application = () ->
if # instenceof Application
console.log "CONSTRUCTOR INIT"
Application::test = () ->
"TEST"
Version = #Version = '0.0.0.1'
)()
Main App:
require './Application'
App = new Appication()
console.log App.test()
console.log Version

How's this:
global[k] = v for k,v of require './utils'

something like that is a good approach to my opinion:
utils.coffee
module.exports =
foo: ->
"foo"
bar: ->
"bar"
main.coffee
util = require "./util"
console.log util.foo()

Related

Extend module with global configuration without breaking current usages

I want to extend a current Node.js module with some global config setting being configured once without breaking current usages of this module.
This is the signature of the module:
const myFunction = function(someOptions) { ... };
module.exports = myFunction;
Usage is
const myFunction = require('myfunction');
const result = myFunction(options);
Now I want to set some options on application startup to be used by the module myfunction whenever being required without breaking current usages of the module myfunction.
If possible, I want to avoid using Node.js global.
Functions in JavaScript are just objects, so you can give them properties. This is a little hacky, but it could certainly work for you:
// greeter.js
function sayHello() {
const message = sayHello.message || "Hi";
console.log(message);
}
module.exports = sayHello;
You can now set the config of this function globally as follows:
const sayHello = require("./greeter.js");
sayHello.message = "S'up dawg";
Any subsequent calls to sayHello() after the code above is executed will use the overridden message. This works because calls to require() are cached, so each time you require(./greeter.js); you're getting back exactly the same function object.

Best way to invoke code inside a module in nodejs

From a performance perspective, is there any difference between invoking code by wrapping it in a function and then exporting it:
function doSomething () {
// doing something here
}
module.exports = doSomething();
And just requiring it without any exports? like this:
myModule.js
// Code doing something
file that requires the module:
var doSomething = require('./myModule');
And if the purpose of the code inside the module is to run just once, do I need to store it in a variable?
If you don't need the return value of that function, then you don't have to store it in a variable.
The difference with:
function doSomething () {
// doing something here
}
module.exports = doSomething();
and using:
var x = require('module');
var y = require('module');
vs.
function doSomething () {
// doing something here
}
module.exports = doSomething;
and using:
var x = require('module')();
var y = require('module')();
is that in the first case, the function will be run only once, while in the second case the function will be run twice.
The difference is that if you just include it without module.exports, then the code will execute immediately but be private to the module. You can only access the data if you export it somehow, with module.exports. It can be either a function or a Javascript Object. Essentially, you can view everything within the module as being completely hidden from everything else in your application.
The only shortcut that I know of is for JSON files. If you look here: Module.exports vs plain json for config files, you can see that you can require('file.json') and it will replace the contents of the json file with a Javascript object that you can then use in your application.

How to share a certain instance with multiple modules in Node.js?

Suppose that I have my main.js module, a shared.js and a foo.js modules.
main.js file is the following:
function Main(){
this.shared = new Shared();
}
Main.prototype.getFoo(){
return new Foo();
}
Now, in order to work Foo needs the 'shared' instance created in Main, Is there an approach I could take other than passing 'shared' to Foo so that Foo can always access that 'shared' instance?
Edit: Main is instantiated once.
You may use global variables to do this but this is not the propper way. Far better you can use require() to do this. In the main.js add the following:
module.exports = Main;
Now in any other module you need this only require it.
var Main = require('./main.js');
That's it. This works also between different packages.
I was able to solve this problem by directly passing the shared instance to the exports.
shared.js:
module.exports = new Shared();
function Shared(){
...
}
main.js:
function Main(){
this.shared = require('./shared.js');
}
Main.prototype.getFoo = function(){
return new Foo();
}
foo.js:
function Foo(){
this.shared = requrie('./shared.js');
}
This way Foo will use the same 'shared' instance used in Main without having to pass it. I'm not sure if this is a 'correct' way to achieve my needs but is doing its job.

NodeJS: Static imports possible?

Question in short:
Is there a way to statically import functions of another JS file in NodeJS? (As the static-import of Java?)
Example of what I'd like to do:
I have a file m1.js which contains functions:
function add(x,y) { return x + y }
exports.add = add
Then I have a file app.js which imports m1.js:
m1 = require('./m1')
var result = m1.add(3,4)
Now, what I'd like to do is to import the functions of m1.js such that i can call them, without having to prefix the calls with m1.*:
m1 = require('./m1')
var result = add(3,4) // instead of m1.add(3,4)
What I've tried so far:
I've tried the following, in the file m1.js:
function add(x,y) { return x + y }
exports.static = function(scope) { scope.add = add }
and tried to import m1.js in app.js as follows but it wasn't able to find add(x,y):
require('./m1').static(this)
var result = add(3,4)
You were close with your attempt. The one small change you have to make is replace this with global when static is called:
require('./m1').static(global)
var result = add(3,4)
From the documentation:
global
{Object} The global namespace object.
In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

Python's 'from ... import *' in Node.js

Is there anything equivarent to Python's 'from foobar import *' in Node.js?
Now I wrote the following code:
var foobar = require('foobar'),
func1 = foobar.func1,
gvar2 = foobar.gvar2,
const3 = foobar.const3;
I think this is ugly, because a lot of names appeared twice.
Python provides smart solution which removes duplications:
from foobar import func1, gvar2, const3
Does Node.js provide similar way?
No, it does not; at least, I am not aware of any way to do this easily.
Node uses the CommonJS module system, which requires a function, require, that returns an exported API for a module.
function mixin(mod,scope)
{
if (!scope)
scope=global;
var module = require(mod);
for (key in module)
scope[key] = module[key];
}
mixin('http');
var s = createServer();

Resources