node.jsmvfs

Move all files in directory to parent with node.js


Question

Is there a simple way to move all the files in a directory up to its parent directory then delete the directory?

Use Case

I'm doing a zip extraction and the source zip contains a root folder called archive, so when I extract I get extract_path/archive/, but I'd like to just extract the contents of archive directly to extract_path.

I thought this would be simple rename, but the following is throwing a "There is a file in the way" error message.

fs.renameSync(extractPath + "/archive", extractPath)

Solution

  • use the mv npm module. mv first tries a fs.rename, and if it fails, uses copy then unlink :

    mv('source/dir', 'dest/a/b/c/dir', {mkdirp: true}, function(err) {
      // done. it first created all the necessary directories, and then
      // tried fs.rename, then falls back to using ncp to copy the dir
      // to dest and then rimraf to remove the source dir
    });
    

    or spawn a child process :

    var spawn = require('child_process').spawn,
        mv = spawn('mv', ['/dir1/dir2/*','dir1/']);