Reputation: 9811
I'm getting started with some modern Javascript, I decided to use Nodejs because it appears to be the most popular framework for JS on the desktop at the moment, I don't understand both why my code doesn't work and the associated error message that I get.
Consider this snippet
var a = 5;
var func = function(){return arguments.length;};
process.stdout.write(+func(1,2,3,a));
It doesn't work and it generates the following error message
net.js:612
throw new TypeError('invalid data');
^
TypeError: invalid data
at WriteStream.Socket.write (net.js:612:11)
at Object.<anonymous> (var_1.js:3:16)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
I'm a C/C++ programmer and this is absolutely cryptic to me, moreover I used a +
before invoking func
to make sure that the result is an integer
, so why write
is complaining at all ?
After some nonsense adding a + '\n'
makes this code work
var a = 5;
var func = function(){return arguments.length;};
process.stdout.write(+func(1,2,3,a) + '\n');
Anyone can explain what's going on ?
Upvotes: 7
Views: 9452
Reputation: 795
var writeBuffer = Buffer(1);
writeBuffer[0] = 1; //Value to be written
process.stdout.write(writeBuffer);
Upvotes: 1
Reputation: 123563
The 1st argument given to .write()
is expected to be a String
or Buffer
. Number
s aren't allowed.
process.stdout.write(func(1,2,3,a).toString());
process.stdout.write(String(func(1,2,3,a)));
The Addition operator (a + b
) does this conversion implicitly when concatenating '\n'
.
Upvotes: 11
Reputation: 145162
You can only write strings or Buffer
s to sockets. (stdout
is a socket.) As a integer is not a string or a buffer, trying to write it to stdout
is an error.
Concatenating a string to an integer coerces (converts) the integer to a string, which is why it worked. You could concatenate an empty string (i+''
) or call the integer's toString
method.
Upvotes: 2