Prevent Node.js repl from printing output

拈花ヽ惹草 提交于 2019-12-17 19:38:08

问题


If the result of some javascript calculation is an array of 10,000 elements, the Node.js repl prints this out. How do I prevent it from doing so?

Thanks


回答1:


Why don't you just append ; null; to your expression?

As in

new Array(10000); null;

which prints

null

or even shorter, use ;0;




回答2:


Assign the result to a variable declared with var. var statements always return undefined.

> new Array(10)
[ , , , , , , , , ,  ]

> var a = new Array(10)
undefined



回答3:


Node uses inspect to format the return values. Replace inspect with a function that just returns an empty string and it won't display anything.

require('util').inspect = function () { return '' };




回答4:


You could start the REPL yourself and change anything that annoys you. For example you could tell it not to print undefined when an expression has no result. Or you could wrap the evaluation of the expressions and stop them from returning results. If you do both of these things at the same time you effectively reduce the REPL to a REL:

node -e '
    const vm = require("vm");
    require("repl").start({
        ignoreUndefined: true,
        eval: function(cmd, ctx, fn, cb) {
            let err = null;
            try {
                vm.runInContext(cmd, ctx, fn);
            } catch (e) {
                err = e;
            }
            cb(err);
        }
    });
'



回答5:


Javascript has the void operator just for this special case. You can use it with any expression to discard the result.

> void (bigArray = [].concat(...lotsOfSmallArrays))
undefined



回答6:


I have already said in a comment to this question that you may want to wrap the execution of your command in an anonymous function. Let's say you have some repeated procedure that returns some kind of result. Like this:

var some_array = [1, 2, 3];

some_array.map(function(){

    // It doesn't matter what you return here, even if it's undefined
    // it will still get into the map and will get printed in the resulting map
    return arguments;
});

That gives us this output:

[ { '0': 1,
    '1': 0,
    '2': [ 1, 2, 3 ] },
  { '0': 2,
    '1': 1,
    '2': [ 1, 2, 3 ] },
  { '0': 3,
    '1': 2,
    '2': [ 1, 2, 3 ] } ]

But if you wrap the map method call into a self-invoking anonymous function, all output gets lost:

(function(){
    some_array.map(function() {
        return arguments;
    });
})();

This code will get us this output:

undefined

because the anonymous function doesn't return anything.



来源:https://stackoverflow.com/questions/13683577/prevent-node-js-repl-from-printing-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!