如何在节点中转义shell命令的字符串? [英] How do I escape a string for a shell command in node?

查看:210
本文介绍了如何在节点中转义shell命令的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

nodejs 中,执行外部命令的唯一方法是通过sys.exec(cmd)。我想调用一个外部命令,并通过stdin给它数据。在nodejs中,似乎没有一种打开命令的方法,然后将数据推送到它(仅执行并接收其标准+错误输出),所以现在看来​​我唯一必须这样做的方法是通过单个字符串命令,如:

In nodejs, the only way to execute external commands is via sys.exec(cmd). I'd like to call an external command and give it data via stdin. In nodejs there does yet not appear to be a way to open a command and then push data to it (only to exec and receive its standard+error outputs), so it appears the only way I've got to do this right now is via a single string command such as:

var dangerStr = "bad stuff here";
sys.exec("echo '" + dangerStr + "' | somecommand");

对这样的问题的大多数答案都集中在正则表达式,这对于nodejs不适用于我它使用Google的V8 Javascript引擎)或来自其他语言(如Python)的本机功能。

Most answers to questions like this have focused on either regex which doesn't work for me in nodejs (which uses Google's V8 Javascript engine) or native features from other languages like Python.

我想逃避dangerStr,因此可以安全地撰写一个像这样的exec字符串以上。如果有帮助的话,dangerStr将包含JSON数据。

I'd like to escape dangerStr so that it's safe to compose an exec string like the one above. If it helps, dangerStr will contain JSON data.

推荐答案

有一种写入外部命令的方法: process.createChildProcess 文档)返回一个对象,其中包含写入方法。 createChildProcess 并不方便,因为它不缓冲stdout和stderr,所以你需要事件处理程序来读取块中的输出。

There is a way to write to an external command: process.createChildProcess (documentation) returns an object with a write method. createChildProcess isn't as convenient though, because it doesn't buffer stdout and stderr, so you will need event handlers to read the output in chunks.

var stdout = "", stderr = "";
var child = process.createChildProcess("someCommand");

child.addListener("output", function (data) {
    if (data !== null) {
        stdout += data;
    }
});
child.addListener("error", function (data) {
    if (data !== null) {
        stderr += data;
    }
});
child.addListener("exit", function (code) {
    if (code === 0) {
        sys.puts(stdout);
    }
    else {
        // error
    }
});

child.write("This goes to someCommand's stdin.");

这篇关于如何在节点中转义shell命令的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆