How do I move file a to a different partition or device in Node.js?

后端 未结 5 1141
终归单人心
终归单人心 2020-11-30 04:36

I\'m trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link.

相关标签:
5条回答
  • 2020-11-30 05:13

    to import the module and save it to your package.json file

    npm install mv --save
    

    then use it like so:

    var mv = require('mv');
    
    mv('source_file', 'destination_file', function (err) {
        if (err) {
            throw err;
        }
        console.log('file moved successfully');
    });
    
    0 讨论(0)
  • 2020-11-30 05:19

    I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:

    require('child_process').spawn('cp', ['-r', source, destination])
    

    What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.

    I know it's not the most elegant, but it did what I needed :)

    0 讨论(0)
  • 2020-11-30 05:21

    One more solution to the problem.

    There's a package called fs.extra written by "coolaj86" on npm.

    You use it like so: npm install fs.extra

    fs = require ('fs.extra');
    fs.move ('foo.txt', 'bar.txt', function (err) {
        if (err) { throw err; }
        console.log ("Moved 'foo.txt' to 'bar.txt'");
    });
    

    I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that @chandru uses.

    0 讨论(0)
  • 2020-11-30 05:23

    You need to copy and unlink when moving files across different partitions. Try this,

    var fs = require('fs');
    //var util = require('util');
    
    var is = fs.createReadStream('source_file');
    var os = fs.createWriteStream('destination_file');
    
    is.pipe(os);
    is.on('end',function() {
        fs.unlinkSync('source_file');
    });
    
    /* node.js 0.6 and earlier you can use util.pump:
    util.pump(is, os, function() {
        fs.unlinkSync('source_file');
    });
    */
    
    0 讨论(0)
  • 2020-11-30 05:31

    I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.

    Just install move-file:

    $ npm install move-file
    

    Then use it like this:

    const moveFile = require('move-file');
    
    (async () => {
        await moveFile(fromPath, toPath);
        console.log('File moved');
    })();
    
    0 讨论(0)
提交回复
热议问题