You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

渲染后的字符串传入exec()时"被移除,如何避免该问题?

问题描述

我用Nunjucks模板渲染后得到如下字符串:

something something '{"firstName": "john", "lastName": "doe", "age": 12}'

但将其传入exec()后,被解析成了:

something something '{firstName: john, lastName: doe, age: 12}'

引号被shell解析去掉,导致JSON格式失效。示例代码如下:

function getCommand(){
    // 渲染模板
    return renderedString;
}

const command = getCommand();
exec(command);
解决方案

要避免shell解析时丢失引号,有两种可靠的处理方式:

1. 对JSON字符串进行Shell转义

exec()会通过系统shell解析命令字符串,即便用单引号包裹,shell仍可能解析内部引号。你需要对JSON部分做shell转义,确保它被完整传递。

可以使用shell-escape工具包处理:

  • 安装依赖:npm install shell-escape
  • 修改代码:
const shellEscape = require('shell-escape');

function getCommand(){
    const jsonData = {"firstName": "john", "lastName": "doe", "age": 12};
    // 先序列化JSON,再做shell转义
    const escapedJson = shellEscape([JSON.stringify(jsonData)]);
    return `something something ${escapedJson}`;
}

const command = getCommand();
exec(command);

转义后的命令会被shell正确识别,JSON内的引号不会被解析丢失。

2. 使用execFile()替代exec()

execFile()不通过shell解析命令,直接执行可执行文件,参数单独传入,从根源避免shell解析的问题,同时还能防止命令注入风险。

示例代码:

const { execFile } = require('child_process');

function getCommandParts(){
    // 拆分命令主体和参数
    return ['something', 'something', '{"firstName": "john", "lastName": "doe", "age": 12}'];
}

const [command, ...args] = getCommandParts();
execFile(command, args, (error, stdout, stderr) => {
    // 处理执行结果
});

这种方式无需处理shell转义,参数会完整传递给目标程序。

内容的提问来源于stack exchange,提问作者ian bart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:43:19