如何从 nodejs spawn 调用 "find -exec"

How to call "find -exec" from nodejs spawn

我有一个遗留的 perl 应用程序发布脚本,我正在尝试用 nodejs 重新编写它。

发布过程的一部分涉及为子文件夹中的所有文件设置正确的属性。

在 perl 发布脚本中,这是使用反引号完成的,就像这样...

my $command = `find '$code_folder' -type f -exec chmod 644 {} +`;

这很好用。

我在将其转换为在 node 中工作时遇到问题。

我正在尝试使用 "spawn" npm 模块,就像这样...

const chalk = require("chalk"),
    spawn = require('child_process').spawn;

let childProcess = spawn('find',['test_folder','-type','f','-exec chmod 644 {} +'],{});

childProcess.stdout.on('data', function (data) {
    console.log(chalk.green(data.toString()));
});

childProcess.stderr.on('data', function (data) {
    console.log(chalk.red(data.toString()));
});

childProcess.on('close', (code) => {
    if (code === 0) {
        console.log(chalk.blue(`exit_code = ${code}`));
    }
    else {
        console.log(chalk.yellow(`exit_code = ${code}`));
    }
});

childProcess.on('error', (error) => {
    console.log(chalk.red(error.toString()));
});

当我尝试 运行 时,出现以下错误...

find: unknown predicate `-exec chmod 644 {} +'

如果我省略了 -exec 部分,命令 运行s 会按预期显示所有文件。

我已经尝试了所有我能想到的以不同的方式转义它,但找不到让它接受“-exec”参数的方法。

此外,我应该提一下,我也尝试了以下...

let childProcess = spawn('find',['test_folder','-type','f','-exec','chmod 644 {} +'],{});

它给出了错误...

find: missing argument to `-exec'

更新: 我找到了一种方法来做到这一点。虽然看起来有点老套。如果有人知道正确的方法,请告诉我。

以下作品...

let childProcess = spawn('sh',['-c', 'find test_folder -type f -exec chmod 644 {} +'],{});

因此,它不会生成 'find' 进程,而是生成 'sh -c',并将 'find' 命令作为参数传递给它。

找到所有文件后,您可以使用 fs module 更改权限。我使用的是 Node 10,所以如果您之前使用过任何东西,您可能需要稍微更改一下语法。

const { chmodSync } = require('fs')
const {execFileSync} = require('child_process')

execFileSync('find',['test_folder', '-type', 'f'])
 .toString() // change from buffer to string
 .trim() //remove the new line at end of the file
 .split('\n') // each file found as array element
 .forEach(path => chmodSync(path, '644')) // Set chmod to 644

如果要使用 spawn 方法,则必须将每个参数作为单独的数组元素传递,如下所示:

const spawn = require('child_process').spawn;

const childProcess = spawn(
   'find',
   ['test_folder', '-type', 'f', '-exec', 'chmod', '644', '{}', '+'],
   {}
);

但我建议使用 exec 方法。对于您的用例,它们应该是相同的,但 exec 具有更好的界面。它接受整个命令作为字符串和 returns 缓冲响应,因此您不需要手动管理流。这是一个例子:

const exec = require('child_process').exec;

exec('find test_folder -type f -exec chmod 644 {} +', (error, stdout, stderr) => {
   console.log(error, stdout, stderr);
});