node.js - Доступ к коду выхода и stderr системной команды

Я придумал довольно простую реализацию на Java с использованием регулярных выражений:

public static Comparator<String> naturalOrdering() {
    final Pattern compile = Pattern.compile("(\\d+)|(\\D+)");
    return (s1, s2) -> {
        final Matcher matcher1 = compile.matcher(s1);
        final Matcher matcher2 = compile.matcher(s2);
        while (true) {
            final boolean found1 = matcher1.find();
            final boolean found2 = matcher2.find();
            if (!found1 || !found2) {
                return Boolean.compare(found1, found2);
            } else if (!matcher1.group().equals(matcher2.group())) {
                if (matcher1.group(1) == null || matcher2.group(1) == null) {
                    return matcher1.group().compareTo(matcher2.group());
                } else {
                    return Integer.valueOf(matcher1.group(1)).compareTo(Integer.valueOf(matcher2.group(1)));
                }
            }
        }
    };
}

Вот как это работает:

final List<String> strings = Arrays.asList("x15", "xa", "y16", "x2a", "y11", "z", "z5", "x2b", "z");
strings.sort(naturalOrdering());
System.out.println(strings);

[x2a, x2b , x15, xa, y11, y16, z, z, z5]

24
задан Baum mit Augen 18 November 2017 в 22:51
поделиться

2 ответа

Вам понадобится асинхронная / обратная версия exec. Возвращено 3 значения. Последние два - это стандартный вывод и стандартный вывод. Также child_process является источником событий. Послушайте событие exit. Первым элементом обратного вызова является код выхода. (Очевидно из синтаксиса, вы захотите использовать узел 4.1.1, чтобы код ниже работал так, как написано)

const child_process = require("child_process")
function systemSync(cmd){
  child_process.exec(cmd, (err, stdout, stderr) => {
    console.log('stdout is:' + stdout)
    console.log('stderr is:' + stderr)
    console.log('error is:' + err)
  }).on('exit', code => console.log('final exit code is', code))
}

Попробуйте следующее:

`systemSync('pwd')`

`systemSync('notacommand')`

И вы получит:

final exit code is 0
stdout is:/
stderr is:

Далее:

final exit code is 127
stdout is:
stderr is:/bin/sh: 1: notacommand: not found
8
ответ дан bbuckley123 18 November 2017 в 22:51
поделиться

Вы также можете использовать child_process.spawnSync() , поскольку он возвращает гораздо больше:

return: 
pid <Number> Pid of the child process
output <Array> Array of results from stdio output
stdout <Buffer> | <String> The contents of output[1]
stderr <Buffer> | <String> The contents of output[2]
status <Number> The exit code of the child process
signal <String> The signal used to kill the child process
error <Error> The error object if the child process failed or timed out

Таким образом, код выхода, который вы ищете, будет ret.status.

5
ответ дан infografnet 18 November 2017 в 22:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: