# 命令行操作 `child_process` ## 基础类 `spwan` ### 输入参数 1. `command` 要执行的命令 2. `command params` 命令行后面携带的参数 3. `options` 执行参数 - `cwd` 执行命令的目录位置 - `shell` 是否开启`shell`执行命令,在win下常用(据说) ### 返回 spawn 对象 1. `stdin` 程序标准输入 > 需要继续深入研究.可处理用户输入 2. `stdout` 程序标准输出事件 3. `stderr` 程序标准错误事件 一般程序`warning`级别的输出也会在`stderr`中进行输出, 4. `close` 程序关闭事件 ### 示例 通过`nodejs`调用`ffmpeg`将`h264`文件制作封面与转码操作 ```js function videoToMp4Spawn(filePath,targetPath){ filePath = path.join(filePath); // -i ${filePath} -y -f image2 -s 3 -vframes 1 ${targetPath}.jpg let ffmpeg = process.spawn('ffmpeg', ['-i',filePath,'-y','-f','image2','-ss','3','-vframes','1',`${targetPath}.jpg`,'-loglevel', 'error']) ffmpeg.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ffmpeg.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ffmpeg.on('close', (code) => { console.log(`--------------------\n\n\n`); console.log(`child process exited with code ${code}`); // 任务结束 }); let taransformFfmepg = process.spawn('ffmpeg',['-i',filePath,`${targetPath}.mp4`,'-loglevel', 'error']) taransformFfmepg.stdout.on('data', (data) => { console.log(`[taransformFfmepg] stdout: ${data}`); }); taransformFfmepg.stderr.on('data', (data) => { console.log(`[taransformFfmepg] stderr: ${data}`); }); taransformFfmepg.on('close', (code) => { console.log(`--------------------\n\n\n`); console.log(`[taransformFfmepg] child process exited with code ${code}`); // 任务结束 }); } videoToMp4Spawn('./public/1.264','./public/r'); ``` ### 注意事项 执行命令行程序时记得将程序输出级别调整成自己需要的`warn`或者`error`级别