Is there dojo.hitch equivalent in node.js - node.js

I am looking for a function that kind bind the 'this' of a function. Although it is easy to write one, I want to be sure that it is not part of any popular module in node.js environment before I write or use the one from dojo.

(function() {
alert(this.toString());
}).bind(new String("Man ES5 is awesome.")).call();
Function.prototype.bind[docs]
Node.js runs on V8. V8 is fully ES5 compliant.

Related

How to modify NodeJS built-in global objects?

I'd like to add an important functionality that I can use at work without using require() every time. So, I thought modifying built-in objects can make this happen but I could not locate the locations of those objects to do the modification.
Are those objects in NodeJS binary? Would that mean I have to fork the whole NodeJS repo to make this happen?
Please, I don't want to use prototype editing etc which are same as require. I need to have native feeling.
First off, I agree with an earlier comment that this sounds like a bit of an XY problem where we could better help you if you describe what problem you're really trying to solve. Portable node.js programs that work anywhere or work with any future versions of node.js don't rely on some sort of custom configured environment in order to run. They use the built-in capabilities of node.js and they require/import in external things they want to add to the environment.
Are those objects in NodeJS binary?
Yes, they are in the executable.
Would that mean I have to fork the whole NodeJS repo to make this happen?
Yes.
Please, I don't want to use prototype editing etc which are same as require. I need to have native feeling.
"Native feeling"? This sounds like you haven't really bought into the node.js module architecture. It is different than many other environments. It's easy to get used to over time. IMO, it would really be better to go with the flow and architecture of the platform rather than make some custom version of node.js just to save one line of typing in your startup code.
And, the whole concept of adding a number of globals you can use anywhere pretty much shows that you haven't fully understood the design, architectural, code reuse and testability advantages of the module design baked into node.js. If you had, you wouldn't be trying to write a lot of code that can't be reused in other ways that you don't anticipate now.
That said, in searching through the node.js source code on Github, I found this source file node.js which is where lots of things are added to the node.js global object such as setTimeout(), clearTimeout(), setImmediate(), clearImmediate() and so on. So, that source file seems to be where node.js is setting up the global object. If you wanted to add your own things there, that's one place where it would be done.
To provide a sample of that code (you can see the link above for the complete code):
if (!config.noBrowserGlobals) {
// Override global console from the one provided by the VM
// to the one implemented by Node.js
// https://console.spec.whatwg.org/#console-namespace
exposeNamespace(global, 'console', createGlobalConsole(global.console));
const { URL, URLSearchParams } = require('internal/url');
// https://url.spec.whatwg.org/#url
exposeInterface(global, 'URL', URL);
// https://url.spec.whatwg.org/#urlsearchparams
exposeInterface(global, 'URLSearchParams', URLSearchParams);
const {
TextEncoder, TextDecoder
} = require('internal/encoding');
// https://encoding.spec.whatwg.org/#textencoder
exposeInterface(global, 'TextEncoder', TextEncoder);
// https://encoding.spec.whatwg.org/#textdecoder
exposeInterface(global, 'TextDecoder', TextDecoder);
// https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope
const timers = require('timers');
defineOperation(global, 'clearInterval', timers.clearInterval);
defineOperation(global, 'clearTimeout', timers.clearTimeout);
defineOperation(global, 'setInterval', timers.setInterval);
defineOperation(global, 'setTimeout', timers.setTimeout);
defineOperation(global, 'queueMicrotask', queueMicrotask);
// Non-standard extensions:
defineOperation(global, 'clearImmediate', timers.clearImmediate);
defineOperation(global, 'setImmediate', timers.setImmediate);
}
This code is built into the node.js executable so the only way I know of to directly modify it (without hackish patching of the executable itself) would be to modify the file and then rebuild node.js for your platform into a custom build.
On a little more practical note, you can also use the -r module command line argument to tell node.js to run require(module) before starting your main script. So, you could make a different way of starting node.js from a shell file that always passes the -r fullPathToYourModule argument to node.js so it will always run your startup module that adds things to the global object.
Again, you'd be doing this just to save one line of typing in your startup file. It is really worth doing that?

Can I expose a commonjs module object in the global namespace?

We're building a react/flux application using nodejs/webpack and therefore all of our new code is written in commonjs modules.
There are a few isolated cases where we need to access an object from one of our commonjs modules in legacy code. Is there any way to do this...and yes, I assume this is gross. We're eventually going to migrate all of our code to commonjs modules, but this is a stop-gap.
In the legacy JS code (non using CommonJS), create a function in the global namespace:
/* Legacy code NOT using CommonJS */
function getCommonJSObject(obj) {
...
}
In the CommonJS code you can test for this global function and if it exists, call it, passing whichever object you need access to.
/* CommonJS object */
if(window['getCommonJSObject']){
window.getCommonJSObject(obj);
}
By doing this we can still follow our flux pattern from legacy javascript code in our app. If there's a better way to do this, let us know. But this is a handy workaround.

node-migrate: can I use es6 import in migration script?

With node-migration npm package can I use es6 imports
I want to do:
import dash from './utils/rethinkdb';
let r = dash();
exports.up = function(next){
next();
};
exports.down = function(next){
next();
};
I know that i can just require, but I am writing everything in es6 so, wanted to be consistent
Thx
It does not necessarily depend on the migration framework you use, but on node.js itself.
Node.js has a "bit" of support for ES6 already, by using the --harmony flag. Take a look at it, if all your features you want are covered by --harmony, this might be an option:
https://github.com/joyent/node/wiki/es6-%28a.k.a.-harmony%29-features-implemented-in-v8-and-available-in-node
Another option is to use https://babeljs.io/ to transpile your code back to ES5 in order to run it.
Also note, if you're using io.js, you have to know that io.js doesn't handle the --harmony flag exactly the same as node does. All you need to know about this, you can read here:
https://iojs.org/en/es6.html

Load a chaplin module synchronously

I'm trying to just load the event_broker module in the chaplinjs . I am able to to do by doing something like
require(["underscore", "chaplin"], function(_, chaplin)
{
var eventBroker = _({}).extend(chaplin.EventBroker);
});
But, this is not good enough in my case. I need to be able to load the event_broker module synchronously. I know that is what require designed to do. Is there a way to do that?
I know that is what require designed to do.
No, that's not what RequireJS is designed to do. (Did you forget to put "not" in there?) RequireJS is designed to load modules asynchronously.
I would normally suggest loading Chaplin through a script element because that would be synchronous but, after looking at the code of Chaplin, I see that it fails with throw new Error('Chaplin requires Common.js or AMD modules'); if it does not detect a CommonJS or AMD environment.
Almond can be used to load bundles of AMD modules synchronously so this may be an option for you.

Write a module that works both in nodejs and requirejs

I wrote a small parser that currently works in node app, but wondering if there is a way that I can make a module that will work both in NodeJS app and client side app that uses requirejs?
path/to/lib/index.js
function someRandom(strings) {
// we are doing something here
return strings
}
exports.someRandom = someRandom;
Right now I'm getting this in client-side
Uncaught ReferenceError: exports is not defined
I know that I can use node requirejs and then change the structure to use define but is there other way without adding node requirejs?
This is my js/main.js file
require(["path/to/lib/index"], function(something) {
// will do something here
});
The way I prefer to do it is to write all my modules in the AMD syntax (use define) and use amd-loader to load them in Node. Note that this solution is not using RequireJS, even though the AMD syntax is used.
However, there's a way to do it without having to use the AMD syntax. You can use r.js to wrap your Node modules. For instance, if you put your tree of Node modules in in, you can do:
$ r.js -convert in out
This will create in out a tree of files that correspond to those in in but wrapped with the define call. You can then load these in the browser using RequireJS. There are limitations. Some are obvious, like not being able to use the Node modules that depend on the Node runtime (like fs, child_process, etc.). Some are more subtle, like the fact that you can't use require(foo) where foo is a variable (RequireJS will handle only string literals there). See the documentation for the details.

Resources