节点:2D数组未填满

时间:2017-05-22 08:21:03

标签: javascript arrays node.js

您好我试图创建一个函数,返回客户端计算机上已安装程序的版本号。到目前为止,我得到了版本号,但现在我试图将它们存储到2d阵列中以便以后使用它们。

我的功能:

const EventEmitter = require('events');
const spawn = require('child_process').spawn;
const inst = {};

inst.check = (cmd, callback) => {
    let command;
    let res = [
        ['ffmpeg',''],
        ['fpcalc',''],
        ['eyed3','']
    ];
    let pos;
    let count = 0;
    // Spwan all the comands
    for (let i = 0; i < cmd.length; i++) {
        pos = i;
        switch (cmd[i]) {
            case 'ffmpeg':
                command = spawn(cmd[i], ['-version']);
                break;

            case 'fpcalc':
                command = spawn(cmd[i], ['-v']);
                break;

            case 'eyed3':
                command = spawn(cmd[i], ['--version']);
                break;
            default:
        }
        // Add the result to the res array
        command.stdout.on('data', (data) => {
            res[pos][1] = data.toString().slice(15, 20);
            console.log(res[pos][1]);
        });
        command.stderr.on('data', (data) => {
            res[pos][1] = data.toString();
            console.log(res[pos][1]);
        });
        command.on('error', (err) => {
            res[pos][1] = 'error';
            throw err;
        });
    }
    return callback(res);
};

module.exports = inst;

我用这个函数调用函数:

const cmd = ['ffmpeg', 'fpcalc', 'eyed3'];
isInstalled.check(cmd, (res) => {
    console.log(res);
});

但我得到以下结果:

[ [ 'ffmpeg', '' ], [ 'fpcalc', '' ], [ 'eyed3', '' ] ]

有人可以告诉我,我做错了吗?

1 个答案:

答案 0 :(得分:0)

修正了我的自我这是一个异步问题

/*jshint esversion: 6 */
const spawn = require('child_process').spawn;
const asyncLoop = require('node-async-loop');
const inst = {};

inst.check = (cmds, callback) => {
    let command;
    let res = [];
    asyncLoop(cmds, (cmd, next) => {
        switch (cmd) {
            case 'ffmpeg':
                command = spawn(cmd, ['-version']);
                break;

            case 'fpcalc':
                command = spawn(cmd, ['-v']);
                break;

            case 'eyed3':
                command = spawn(cmd, ['--version']);
                break;
        }

        // Add the result to the res array
        command.stdout.on('data', (data) => {
            res.push(data.toString().slice(15, 20));
            next();
        });
        command.stderr.on('data', (data) => {
            res.push(data.toString().trim());
            next();
        });
        command.on('error', (err) => {
            res.push('error');
            next();
        });

    }, (err) => {
        if (err) {
            console.log(`Èrror: ${err.message}`);
            return;
        }
        console.log(`finished:  res = ${res}`);
        return callback(res);
    });
};

module.exports = inst;