Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: Cannot read property 'defaultEncoding' of undefined

I wanted to write a changeable write() function.

var write = function(s) {
    process.stdout.write(s);
}
write("Hello world!");

I thought you could just write it shorter:

var write = process.stdout.write;
write("Hello world!");

But here I will receive this error:

TypeError: Cannot read property 'defaultEncoding' of undefined
    at Writable.write (_stream_writable.js:172:21)
    at Socket.write (net.js:613:40)
    at repl:1:2
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)

Why is that?

like image 230
Artisan72 Avatar asked Feb 11 '23 18:02

Artisan72


1 Answers

It all has to do with how javascript handles this. Inside the function process.stdout.write there is a call to defaultEncoding() using this variable.

In javascript, this is not assigned a value until an object invokes the function where this is defined and it is relative to the calling object.

So in your first example, this points to process.stdout object and it has the method defaultEncoding. In your second example, this is undefined since the function is being called from the global namespace. When process.stdout.write tries to call defaultEncoding, it will throw the error you mentioned.

You can manually define the this value for a function using Function.prototype.call() method. Example:

var write = process.stdout.write;
write.call(process.stdout, "Hello world!");

The first argument of call is the object to be used as this inside the function.

I recommend reading this article, it explains a lot about this in javascript.

like image 86
victorkt Avatar answered Feb 13 '23 08:02

victorkt