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

如何将Node.js中exec执行Shell命令的输出结果转换为数组

思路正确性确认

你提出的先处理回车换行字符的思路完全正确。execShellCommand默认会将shell的全部标准输出作为单个字符串返回,不同行的内容会通过换行符拼接,你看到的单个字符串元素的结构就是这个原因,必须拆分后才能得到可按索引访问的独立元素。

实现方案

方案1:字符串拆分处理(兼容度最高)

适配不同操作系统的换行格式,同时过滤掉末尾换行带来的空元素:

// 注意如果你的execShellCommand返回的是包裹了一层的数组,先取[0]再处理
const shellOutput = await execShellCommand('aws cloudwatch list-metrics --namespace AWS/ApiGateway  | jq -r .Metrics[].Dimensions[].Name | sort -u')
const uniqueMetrics = shellOutput.split(/\r?\n/).filter(item => item.trim() !== '')

// 即可按索引访问
console.log(uniqueMetrics[0]) // ApiId
console.log(uniqueMetrics[1]) // ApiName
  • 正则/\r?\n/可同时匹配Windows风格的\r\n和Unix风格的\n换行符
  • filter步骤用于过滤命令输出末尾自带换行产生的空字符串元素

方案2:结构化输出(稳定性最优)

直接修改shell命令,通过jq输出JSON结构的结果,Node.js侧直接解析即可,无需处理换行逻辑:

const shellOutput = await execShellCommand('aws cloudwatch list-metrics --namespace AWS/ApiGateway  | jq -r "[.Metrics[].Dimensions[].Name] | unique"')
const uniqueMetrics = JSON.parse(shellOutput)

该方案完全规避了换行、特殊字符带来的解析异常问题,适合生产环境使用。

如果你实际拿到的execShellCommand返回结果是[ 'ApiId\r\nApiName\r\nStage\r\n' ]这种外层包裹数组的结构,处理前先取下标为0的元素即可:

const rawResult = await execShellCommand('你的命令')
const uniqueMetrics = rawResult[0].split(/\r?\n/).filter(item => item.trim())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:15:08