在Node.js中,为什么我的spawn命令会产生错误?

在Node.js中,为什么我的spawn命令会产生错误?,node.js,Node.js,当我跑步时: unzip -p /tmp/document.docx word/document.xml | sed -e 's/<\/w:p>/\\n/g; s/<[^>]\{1,\}>//g; s/[^[:print:]\n]\{1,\}//g' unzip-p/tmp/document.docx word/document.xml | sed-e的/\\n/g;s/]\{1,\}>//g;s/[^[:print:][\n]\{1,\}//g' 它正确地从m

当我跑步时:

unzip -p /tmp/document.docx word/document.xml | sed -e 's/<\/w:p>/\\n/g; s/<[^>]\{1,\}>//g; s/[^[:print:]\n]\{1,\}//g'
unzip-p/tmp/document.docx word/document.xml | sed-e的/\\n/g;s/]\{1,\}>//g;s/[^[:print:][\n]\{1,\}//g'
它正确地从my.docx文件中提取文本

但当我尝试将其包装到Node.js程序中时,如下所示:

const spawn = require("child_process").spawn;
const command = "unzip"; ;
const child = spawn("sh", ["-c", "unzip -p /tmp/document.docx word/document.xml | sed -e 's/<\/w:p>/\\n/g; s/<[^>]\{1,\}>//g; s/[^[:print:]\n]\{1,\}//g'"]);


const stdout = child.stdout;
const stderr = child.stderr;
const output = "";

stderr.on("data", function(data) {
    console.error("error on stderr", data.toString());
});


stdout.on("data", function(data) {
    output += data;
 });

stdout.on("close", function(code) {

 });
constspawn=require(“子进程”).spawn;
const命令=“解压”;
const child=spawn(“sh”,[“-c”,“unzip-p/tmp/document.docx word/document.xml | sed-e的//\\n/g;s/]\{1,\}>///g;s/[^[:print:][\n]\{1,\}//g');
const stdout=child.stdout;
const stderr=child.stderr;
常量输出=”;
标准开启(“数据”,功能(数据){
console.error(“stderr上的错误”,data.toString());
});
标准输出打开(“数据”,函数(数据){
输出+=数据;
});
标准输出打开(“关闭”,功能(代码){
});
我收到以下错误消息:

stderr sed上出错:-e表达式#1,字符10:未知选项为's'


如何修复此错误?

在代码中以这种方式使用命令行时,您必须考虑对node.js生成的
\
的解释以及反斜杠反斜杠。一个用于node.js,一个用于sed命令

spawn("sh", ["-c", "unzip -p /tmp/document.docx word/document.xml | sed -e 's/<\\/w:p>/\\\\n/g; s/<[^>]\\{1,\\}>//g; s/[^[:print:]\\n]\\{1,\\}//g'"])
spawn(“sh”、[“-c”、“unzip-p/tmp/document.docx word/document.xml | sed-e的//\\\\n/g;s/]\{1,\\\}>//g;s/[^[:print:][\\n]\{1,\\}//g')

@克劳德

在JavaScript中,反斜杠在字符串和 正则表达式中的文本和文本。如果你想要一个真正的反斜杠 在字符串或正则表达式中,必须写入两个:\


你自己转义字符串的另一种方法是使用带有模板文本字符串的内置函数。我邀请你去看看,如果你觉得有用的话,请投我一票。