ProGamer2711
ProGamer2711

Reputation: 570

How do I grant permissions for fs module nodejs

I'm trying to make a program that needs to check if a folder exists. If it does - it deletes and creates it again (to clear it). If it doesn't - it creates it. After that I copy all paths that get returned from a function into that cleared folder. I'm currently running into errors for permssions to delete the folder and also errors for copying the file. I tried chmodSync but I couldn't work it out. Here's my code:

function sortTracks(dir) {
    fs.chmodSync(
        path.join(dir, "playlist"),
        fs.constants.S_IRUSR | fs.constants.S_IWUSR
    );
    if (fs.existsSync(path.join(dir, "playlist")))
        fs.rmdirSync(path.join(dir, "playlist"));

    fs.mkdirSync(path.join(dir, "playlist"));

    fs.chmodSync(
        path.join(dir, "playlist"),
        fs.constants.S_IRUSR | fs.constants.S_IWUSR
    );
    getAllFiles(dir, []).forEach(track => {
        fs.chmodSync(track, fs.constants.S_IRUSR);
        fs.copyFileSync(track, path.join(dir, "playlist"));
    });
}

Upvotes: 0

Views: 1184

Answers (1)

Itai Steinherz
Itai Steinherz

Reputation: 817

From what I could tell, sortTracks attempts to:

  1. Set the permissions of ${cwd}/playlist to be readable and writeable by the user
  2. Remove ${dir}/playlist if it already exists
  3. Create the ${dir}/playlist directory
  4. Set the permissions of ${dir}/playlist, as done in step #2
  5. For each file returned by getAllFiles(dir, []):
    1. Set its permissions to be readable by the user
    2. Copy it to ${dir}/playlist

A few things that stood out to me:

  • Step #1 is redundant. You can see it for yourself - try running the following in bash:

    $ mkdir a
    $ chmod -rw a
    $ rm -rf a
    

    You'll see that a gets created and removed.

  • Step #4 is redundant. The default permissions for a directory make it readable & writeable.

  • Removing the directory should be done using:

    fs.rmSync(path.join(dir, "playlist"), {recursive: true, force: true});
    

    Instead of fs.rmdirSync (see the docs).

I hope fixing these will resolve the issue for you.

Upvotes: 2

Related Questions