私は、実際の端末でコマンドを実行したときとは別の出力をchild_process.exec経由でnodejsで実行すると問題が発生します。nodejs execが実際の端末で関数呼び出しよりも他の出力を出す
私のコードは次のようになります。
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);
});
}
私は本当の端末でこのコマンドを実行すると、私はこのようなだけで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で、私は標準出力として、この文字列を取得:
"ine\nt 127.0\n.0.1\nine\nt 192.168\n.178.222"
なぜ出力が似ていないのか、そしてnodejsコールが私に127.0を出力する理由が不思議です。 0.1 IPはコマンドで除外されているためです。