Move File in ExpressJS/NodeJS

前端 未结 4 1923
执笔经年
执笔经年 2021-01-04 18:50

I\'m trying to move uploaded file from /tmp to home directory using NodeJS/ExpressJS:

fs.rename(\'/tmp/xxxxx\', \'/home/user/xxxxx\         


        
相关标签:
4条回答
  • 2021-01-04 19:21

    Another way is to use fs.writeFile. fs.unlink in callback will remove the temp file from tmp directory.

    var oldPath = req.files.file.path;
    var newPath = ...;
    
    fs.readFile(oldPath , function(err, data) {
        fs.writeFile(newPath, data, function(err) {
            fs.unlink(oldPath, function(){
                if(err) throw err;
                res.send("File uploaded to: " + newPath);
            });
        }); 
    }); 
    
    0 讨论(0)
  • 2021-01-04 19:28

    Yes, fs.rename does not move file between two different disks/partitions. This is the correct behaviour. fs.rename provides identical functionality to rename(2) in linux.

    Read the related issue posted here.

    To get what you want, you would have to do something like this:

    var source = fs.createReadStream('/path/to/source');
    var dest = fs.createWriteStream('/path/to/dest');
    
    source.pipe(dest);
    source.on('end', function() { /* copied */ });
    source.on('error', function(err) { /* error */ });
    
    0 讨论(0)
  • 2021-01-04 19:44

    This example taken from: Node.js in Action

    A move() function that renames, if possible, or falls back to copying

    var fs = require('fs');
    module.exports = function move (oldPath, newPath, callback) {
    fs.rename(oldPath, newPath, function (err) {
    if (err) {
    if (err.code === 'EXDEV') {
    copy();
    } else {
    callback(err);
    }
    return;
    }
    callback();
    });
    function copy () {
    var readStream = fs.createReadStream(oldPath);
    var writeStream = fs.createWriteStream(newPath);
    readStream.on('error', callback);
    writeStream.on('error', callback);
    readStream.on('close', function () {
    fs.unlink(oldPath, callback);
    });
    readStream.pipe(writeStream);
    }
    }
    
    0 讨论(0)
  • 2021-01-04 19:45

    Updated ES6 solution ready to use with promises and async/await:

    function moveFile(from, to) {
        const source = fs.createReadStream(from);
        const dest = fs.createWriteStream(to);
    
        return new Promise((resolve, reject) => {
            source.on('end', resolve);
            source.on('error', reject);
            source.pipe(dest);
        });
    }
    
    0 讨论(0)
提交回复
热议问题