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 ?
stdout (1): The standard output stream, which is a source of output from the program. process. stderr (2): The standard error stream, which is used for error messages and diagnostics issued by the program.
process. stdout. write(d); will print the data properly without a new line.
Stdout, also known as standard output, is the default file descriptor where a process can write output. In Unix-like operating systems, such as Linux, macOS X, and BSD, stdout is defined by the POSIX standard. Its default file descriptor number is 1. In the terminal, standard output defaults to the user's screen.
The easiest way to write to files in Node. js is to use the fs. writeFile() API.
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'
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With