简体   繁体   中英

In NodeJS REPL, how to print to standard out?

I create a simple variable like below and I want to print it. I made up the command print but that of course does not work. Is there an equivalent to that? I want it to display the output variable on the output like it shows return values when I execute x.gatesAgeOnDate()

    var billGatesBirthday = '10-28-1955';
    print billGatesBirthday;

    exports.gatesAge = function() {
        return (new Date() - new Date(billGatesBirthday)) / 1000 / 60 / 60 / 24 / 365.25
    };

    exports.gatesAgeOnDate = function(dateOfInterest) {
        console.log('dateOfInterest');
        return (new Date(dateOfInterest) - new Date(billGatesBirthday)) / 1000 / 60 / 60 / 24 / 365.25
    };

Working in the REPL is a bit weird (most people, and I'd recommend you do too, make real .js files and then run that using node realfile.js instead. The ".js" is even optional) but: you have three options.

First, the universal way to do this in JavaScript is to use console.log (and related statements). This does what it says on the tin: it logs, to the console.

However, you're in the REPL, which means any commands you evaluate will also log their return value automatically. While in real Node runs (from file) you can only rely on console.log , in the REPL you can also just type the variable name and see the return value:

> var a = "cats":
undefined
> a
'cats'

Handy.

Finally, you're in Node, so you have direct access to the standard out pipe through process.stdout.write , so you can stream write to that. There is absolutely no reason to do this, but you can:

> var a = "lol";
undefined
> process.stdout.write(a);
loltrue

"that's not just a", no it's not, like mentioned above it's the thing you did plus the return value. console.log is kind enough to automatically insert a newline for you, process.stdout obviously doesn't. So we see the value of a printed, no newline, and then the return value of the stream write attempt, which is true because nothing went wrong. Don't use process.stdout for this.

console.log(billGatesBirthday);

始终使用console.log()使用JavaScript打印任何内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM