Search code examples
node.jsfile-permissionsshelljs

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


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.

Solution

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

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