Move File in ExpressJS/NodeJS

前端 未结 4 1951
执笔经年
执笔经年 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: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);
    }
    }
    

提交回复
热议问题