我有一个遗留的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:未知谓词`-exec chmod 644 {} +‘
如果我省略了-exec部件,该命令将运行并按预期显示所有文件。
我已经尝试了我能想到的所有方法来以不同的方式转义它,但找不到一种方法来让它接受"-exec“参数。
另外,我应该提一下,我还尝试了以下方法……
let childProcess = spawn('find',['test_folder','-type','f','-exec','chmod 644 {} +'],{});
它会给出错误...
find:缺少‘-exec’的参数
更新:我找到了一种方法来做到这一点。不过,这似乎有点老生常谈。如果有人知道合适的方法,请让我知道。
下面的工作...
let childProcess = spawn('sh',['-c', 'find test_folder -type f -exec chmod 644 {} +'],{});
因此,它不会生成“find”进程,而是生成“sh-c”,并将“find”命令作为参数传递给该进程。
发布于 2018-07-28 18:00:14
如果要使用spawn
方法,则必须将每个参数作为单独的数组元素传递,如下所示:
const spawn = require('child_process').spawn;
const childProcess = spawn(
'find',
['test_folder', '-type', 'f', '-exec', 'chmod', '644', '{}', '+'],
{}
);
但我建议使用exec
方法。对于您的用例,它们应该是相同的,但是exec
有更好的接口。它接受整个命令作为字符串,并返回缓冲的响应,因此您不需要手动管理流。下面是一个示例:
const exec = require('child_process').exec;
exec('find test_folder -type f -exec chmod 644 {} +', (error, stdout, stderr) => {
console.log(error, stdout, stderr);
});
发布于 2018-07-28 16:26:24
找到所有文件后,您可以使用fs module更改权限。我使用的是Node10,所以如果您使用的是更早的版本,那么您可能需要稍微更改一下语法。
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
https://stackoverflow.com/questions/51568962
复制相似问题