Skip to content Skip to sidebar Skip to footer

Nodejs: Short Alias For Process.stdout.write

I'm learning nodejs (and I like it!). I tried to figure out how to have shorter alias for console.log and I found out that I can use var cout=console.log and use cout('[string]') f

Solution 1:

You should not do this kind of "short alias". It's very messy and people reading your code won't understand why you use random function names instead of console.log. However, if you really want to create function aliases, consider using a function:

function out(text) {
    //    ^    ^- argument accepted by the function//    |------ the function name
    process.stdout.write(text)
    //                     ^- pass the argument you accepted in your new function to the long function
}

I added some explanation in case you don't know how a function works, you can safely remove it.

Edit: The reason why it's not working is in the source code of Node.JS. The stacktrace you are getting back points to this line:

Writable.prototype.write = function(chunk, encoding, cb) {
    var state = this._writableState;
    // ...
}

It tries to reference a variable called _writableState from this. As written here:

Inside a function, the value of this depends on how the function is called.

This means, that this refers to process.stdout when you call process.stdout.write, however it is undefined, when you call it from your alias. Therefore you get a Cannot read property '_writableState' of undefined exception (as undefined does not contain that variable, which is important for the write function to execute).

Solution 2:

Aside from a function declaration you can also use Function.prototype.bind:

const out = process.stdout.write.bind(process.stdout);
out('foo');

bind returns a new function with the context (this) bound to whatever value you pass. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Post a Comment for "Nodejs: Short Alias For Process.stdout.write"