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

标签 node.js module export undefined

小信息,我有一个 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/

相关文章:

javascript - node.js 本地模块 :cannot find module error

javascript - 当我想使用外部 "_this is undefined"关键字时出现 "this"错误

android - 从适用于 Android 的 Adob​​e Illustrator 导出 .png 时应选择哪些选项?

javascript - 如何创建一个带有附加到对象的方法的 npm 包?

javascript - 截取元素的屏幕截图

javascript - 我不明白关于 node.js 回调的事情

c++ - 如何导出 std::vector

node.js - 如何在 node 中集成 swagger 和 fastify 框架

python - 在 Python 中考虑大小写

c - C 中的 switch 语句和 getopt() 函数