node.js执行cmd
最近在写一个关于语音显示的问题,需要用到node.js执行cmd,记录一下自己的写法
在js文件中
const cp = require('child_process')
//执行cmd
function runCmdTest(inputPath,outputPath) {
let exePath='E:\\2022\\ddd\\src\\http\\voiceConversion\\ypzh.exe' //需要运行的程序
cp.exec(`${exePath} ${inputPath} ${outputPath}`, (err, stdout, stderr) => {
})
}
//node.js写入文件
function writeFile(data, content) {
fs.writeFile(data, content, function (err) {
if (err) {
return console.log("文件写入失败!" + err.message)
}
console.log("文件写入成功!")
})
}
//获取随机数
function wanderNumber(n) {
var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];
global.res = "";
for (var i = 0; i < n; i++) {
var id = Math.ceil(Math.random() * 61);
res += chars[id];
}
return global.res;
}
引用
//文件命名,时间戳加随机数
let audioTempName = "voice" + new Date().getTime() + wanderNumber(4);
let linshiTxt = osCunchu().tmpdir() + "\\" + audioTempName + ".txt";
//建立txt格式文件,osCunchu().tmpdir()获取操作系统临时文件路径(const os = require("os");os.tmpdir())
writeFile(linshiTxt, msg.voip_path);//从后端获取的数据写入到建立的txt文件中
//运行cmd,C:\\Users\\Home\\Desktop\\test这个是用来存放转化后的文件存储地址(mp3),我放在了桌面
runCmdTest(linshiTxt, "C:\\Users\\Home\\Desktop\\test");
最后就会得到一个mp3格式音频了