如何从 console.log(require("child_process").execSync('ls')) 获取文本标准输出?

Jas*_*Jas 1 child-process node.js

如何打印标准输出 console.log(require("child_process").execSync('ls'))

我试过 ts

import { execSync } from 'child_process';
console.log(execSync('ls -la'));
Run Code Online (Sandbox Code Playgroud)

然后编译成js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
console.log(child_process_1.execSync('ls -la'));
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我只得到缓冲区如何获得标准输出?

$ node app.js
$ <Buffer 74 6f 74 61 6c 20 38 38 0a 64 72 77 78 72 2d 78 72 2d 78 20 20 31 31 20 74 6f 6d 65 72 2e 62 65 6e 64 61 76 69 64 20 20 73 74 61 66 66 20 20 20 20 33 ... >
Run Code Online (Sandbox Code Playgroud)

我错过了什么?如何获得文本标准输出?

Ray*_*oal 7

你的最后一行应该是:

console.log(child_process_1.execSync('ls -la').toString());
Run Code Online (Sandbox Code Playgroud)

execSync返回一个缓冲区,只需调用toString该缓冲区即可以字符串形式获取缓冲区的内容。