如果一些JavaScript计算的结果是一个包含10,000个元素的数组,Node.js repl会打印出来。我该如何防止它这样做?
谢谢。
谢谢。
; null;
呢?new Array(10000); null;
打印输出
null
甚至更短的方式,使用;0;
将结果分配给使用var
声明的变量。 var
语句始终返回undefined
。
> new Array(10)
[ , , , , , , , , , ]
> var a = new Array(10)
undefined
Node使用inspect来格式化返回值。将inspect替换为一个只返回空字符串的函数,它就不会显示任何内容。
require('util').inspect = function () { return '' };
> void (bigArray = [].concat(...lotsOfSmallArrays))
undefined
您可以自己启动REPL并更改任何让您感到烦恼的内容。例如,您可以告诉它在表达式没有结果时不要打印undefined
。或者您可以包装表达式的评估并阻止它们返回结果。如果您同时执行这两个操作,则有效地将REPL减少为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);
}
});
'
我已经在对这个问题的评论中说过,您可能想要将命令的执行包装在匿名函数中。假设您有一些重复的过程,返回某种结果。就像这样:
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;
});
这将给我们输出:
[ { '0': 1,
'1': 0,
'2': [ 1, 2, 3 ] },
{ '0': 2,
'1': 1,
'2': [ 1, 2, 3 ] },
{ '0': 3,
'1': 2,
'2': [ 1, 2, 3 ] } ]
map
方法调用封装到一个自执行的匿名函数中,所有输出都会丢失:(function(){
some_array.map(function() {
return arguments;
});
})();
这段代码将会得到以下输出:
undefined
因为匿名函数没有返回任何内容。
0;
比输入匿名函数更短,例如 some_array.map(function(){return arguments;});0;
。 - akuhnBoolean()
或typeof()
中。 - holmberd在 repl 模块中执行此操作。 这将返回一个空字符串作为输出。
const repl = require("repl").start({
writer: (output)=>{
return "";
}
});