gpt4 book ai didi

node.js - module.exports 返回值未定义

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:40 24 4
gpt4 key购买 nike

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

我不明白为什么我的 arpList 函数在我的 index.js 文件中返回未定义的值。

当从index.js调用时,所有console.logs都在arp.js页面中返回正确的值,但ipObj未定义。甚至在我返回 ipObj 之前的 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 添加了一个回调函数 - 函数(子网、回调)

然后不返回值,而是将其传递给回调

然后在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 

不会被退回。 The reference不谈返回值。 Node 式回调很少像这样工作,因为它们可能是异步的,并且无法考虑返回值。

这是 this well-known problem 的特例。该过程是异步的,并在调用arp.arpList(ipSubnet)后完成,没有任何内容可以分配给lanIps。这是 Promise 的一个用例。已经有第三方 promise 的同行,如 child-process-promise .

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

关于node.js - module.exports 返回值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52415771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com