Warm tip: This article is reproduced from stackoverflow.com, please click
file-permissions node.js shelljs

setting custom permissions for the file and inheriting ownership from pattern folder in JS

发布于 2020-03-27 10:21:51

I need to set custom permission and inherit ownership from parent directory after writing to file in JS. I'm using to shelljs to run the commands.

I'm running the following to get the owner and group of the parent directory:

const ownerGroup = shelljs.exec('ls -la ../ | grep -e "`basename $(pwd)`$" | awk \'{print $3, $4}\'').split(' ');

The commands to set the permissions and ownership are as follows:

const owner = ownerGroup[0];
const group = ownerGroup[1];
shelljs.exec(`sudo chown ${owner}:${group} ${process.env.CONFIG_FILE}`);
shelljs.exec(`sudo chmod 660 ${process.env.CONFIG_FILE}`);

The file path is in process.env.CONFIG_FILE. I run into issues with chown as is doesn't see the file path. The command is structured correctly, but the path shifts to the new line.

COMMAND ->  sudo chown yury.stanev:yury.stanev
/home/yury.stanev/menlolab/runner/config.json
chown: missing operand after ‘yury.stanev:yury.stanev’
Try 'chown --help' for more information.
Questioner
Yury Stanev
Viewed
127
Yury Stanev 2019-07-03 22:34

Fixed by replacing any new line character in cmd with nothing.

const cmd = `sudo chown ${owner}:${group} ${process.env.CONFIG_FILE}`.replace('\n', '');