Prevent Node.js repl from printing output

人走茶凉 提交于 2019-11-28 10:56:49

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

As in

new Array(10000); null;

which prints

null

or even shorter, use ;0;

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

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

> var a = new Array(10)
undefined

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 '' };

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);
        }
    });
'

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

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.

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