module.exports return 值未定义

module.exports return value undefined

很少的信息,我有一个 arp.js 文件,它采用子网地址“192.168.2”并从 arp -a 中获取所有字符串 return 并存储在数组中。

我无法弄清楚为什么我的 arpList 函数在我的 index.js 文件中 returning 了一个未定义的值。

当从 index.js 调用时,所有 console.logs 都 return 在 arp.js 页面中输入正确的值,但 ipObj 未定义。即使是 ipObj 的 i return 之前的 console.log 也能正常工作。

如有任何帮助,我们将不胜感激。

var { spawn } = require('child_process');
const arpLs = spawn('arp', ['-a']);
var bufferData;


module.exports = {
    arpList: function (subnet) {


        arpLs.stdout.on('data', data => {
            bufferData += data
        })


        arpLs.stderr.on('data', data => {
            console.log('error: ' + data);
        });


        arpLs.on('exit', function (code) {
            if (code != 0) {
                console.log("Error exiting"); //if error occurs
            }
            console.log("exit start 1"); // checking internal processes at stages
            var dataArray = bufferData.split(' ');
            var ipArray = [];
            for (i = 0; i < dataArray.length; i++) {
                if (dataArray[i].includes(subnet)) {
                    ipArray.push(dataArray[i]);
                    console.log("loop working");
                }
            }
            var ipObj = { "lanIps": ipArray };
            console.log("Object is there: "+ipObj)
            return ipObj; // this obj should be returned to the index.js call using 
        })
    },
    sayMyName: function () {
        return "Hello";
    }
}

//arpList(ipSubnet);
//INDEX.js
//the index page looks like this
//var arp = require('./arp.js);
//var ipSubnet = "192.168.2";

//var lanIps = arp.arpList(ipSubnet);
//console.log(lanIps);

我最终向 arpList 添加了一个回调函数 - 函数(子网,回调)

然后而不是 return 将值传递给回调

然后在 index.js 一边而不是

var lanIps = arp.arpList(value)

我用过

arp.arpList(value, function(res){lanIps = res}
return ipObj; // this obj should be returned to the index.js call using 

它不会被 return编辑。 The reference 什么都不说 return 值。节点式回调很少像那样工作,因为它们可能是异步的,并且无法考虑 returned 值。

这是 this well-known problem. The process is asynchronous and is finished after arp.arpList(ipSubnet) call, there's nothing to assign to lanIps. This is a use case for promises. There are already third-party promisified counterparts like child-process-promise 的特例。

这个问题也可以通过移动到同步来解决API。 child_process 函数具有同步对应项,包括 spawnSync.