nodejs exec在真实terminal中给出比函数调用更多的输出

我有问题,当我通过child_process.exec在nodejs中运行一个terminal命令时,我得到了另一个输出,而不是当我在一个真正的terminal运行命令。

我的代码如下所示:

function checkLocalIP() { logger.debug("Checking the local IP"); execute("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'", function(localIP) { if(isIp.v4(localIP)) { logger.debug("Local IP found",{localIP:localIP}); return true; } else { logger.error("Local IP not found",{localIP:localIP}); return false; } }); } function execute(command, callback){ logger.debug("Executing command: "+command,{command:command}); exec(command, function(error, stdout, stderr){ callback(stdout); }); } 

如果我在一个真正的terminal上运行这个命令,我只能得到这样的IP:

 $ ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' $ 192.168.178.222 

但在nodejs中,我得到这个string作为标准输出:

 "ine\nt 127.0\n.0.1\nine\nt 192.168\n.178.222" 

我想知道为什么输出不相似,为什么nodejs调用也输出我的127.0.0.1 IP,因为它被排除在命令。

记得要逃脱\ 。 请记住,在js中,就像使用C语言或类似的语言一样, \在string中有一个特殊的含义: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation

所以你的string:

 "ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'" 

被解释为:

 ifconfig | grep -Eo 'inet (addr:)?([0-9]*.){3}[0-9]*' | grep -Eo '([0-9]*.){3}[0-9]*' | grep -v '127.0.0.1' 

注意丢失\ 。 这显然导致错误的正则expression式被使用。

要修复它,逃避你的\

 "ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'" 

这是一个很好的问题,我不知道节点为什么这样做。

但也许你可以修复它删除所有的“\ n”字符。 nodejs输出中的“\ n”意味着“行尾”,因此您的search将提供您想要的结果。

也许结果是像下面的图像:

“\ n”表示“行尾”