1

So I've seen several questions similar to this issue but I haven't found anything that quite fixes it.

I'm able to rename a directory with node.js as long as the directory is empty. Once I add contents, I get the error: EPERM: operation not permitted. If I delete the contents, I regain the ability to rename. Is there something simple I'm missing here? Nothing crazy in the code... just can't rename a directory if it has contents.

app.post('/rename', function(req, res, next) {
    let _target = req.body.target,
        _from = req.body.from,
        _to = req.body.to;
    
    fs.renameSync(
        'public/' + _target + '/' + _from,
        'public/' + _target + '/' + _to,
        function(err, data) {
            if (err) { sLog(err); return }
            res.send('File Renamed');
        }
    );
});

-- EDIT --

The issue is when the directory has sub directories. Files in the directory to rename don't seem to affect the action

Styles2304
  • 143
  • 1
  • 14
  • 1
    I would never allow such code, nor in dev not in production (no sanitization, this will allow removing system files!). – Seti Feb 15 '22 at 22:44
  • 1
    As for failing, this should not fail at all, are you sure you are not opening the files somewhere? (I mean, operation not permitted might be raised because something opened even one file from the directory and prevents you from renaming it) – Seti Feb 15 '22 at 22:47
  • As far as security... something to look into sure but this is a private application that will never see the light of day. I don't see much point in advancing if I can't even get the basic functionality to work. As far as failing, no, nothing is opening the file. I literally can execute just fine... if I open the directory and create a sub directory ... the rename fails with `EPERM: operation not permitted`... if I delete the newly created directory ... it works again. – Styles2304 Feb 15 '22 at 22:52
  • 1
    Note: the `fs.renameSync` method doesn't accept a callback function. It's synchronous. – jarmod Feb 15 '22 at 23:00

2 Answers2

0

The issue is that I was using nodemon instead of node. Apparently, as a listener, it was locking the files... once I ran everything as node, it functioned as expected.

Styles2304
  • 143
  • 1
  • 14
0

fs.renameSync doesn't work when the folder is not empty, so you should use another way just like the following:

import fsExtra from "fs-extra";

//then copy and delete, disgusting but work
fsExtra.copySync(oldpath, path);
fsExtra.rmdirSync(oldpath, { recursive: true });
jimmy cao
  • 1
  • 1