如何在node.js中重命名文件?

时间:2014-04-26 23:30:36

标签: node.js

我尝试使用angular和node实现文件上传表单。文件上传很好,但我想扫描上传目录,看看文件名是否已经存在。如果是,则重命名该文件。以下是我到目前为止的情况:

app.post('/file', function(req, res) {
    var fs = require('fs');
    var file = req.files.file;

    // destination directory
    var dest_dir = './uploads;
    var filename = file.name;

    // THIS ISN'T WORKING, I.E., THE FILE IS NOT RENAMED
    fs.readdir(dest_dir, function(err, dir_files) {
        for(var i = 0; i < dir_files.length; i++) {
            if(dir_files[i] == filename) {
                console.log("I can see this message, but the file isn't renamed");
                filename = filename + '_1'; // rename the file
            }
        }
    });

    // read file from temp dir and store in permanent dir
    var source = fs.createReadStream(file.path);
    var dest = fs.createWriteStream(dest_dir + '/' + filename);
    source.pipe(dest);

    source.on('end', function() { res.json("File has been uploaded!") });
    source.on('error', function(err) { res.json("There was an error when attempting to upload this file.") });
});

我做错了什么?

2 个答案:

答案 0 :(得分:2)

在节点中重命名文件有fs.rename()

答案 1 :(得分:0)

fs.readDir()是异步的,所以下面的代码是在fs.readDir()回调中 for 循环之前执行的:

var dest = fs.createWriteStream(dest_dir + '/' + filename);
source.pipe(dest);

如果要在 for 循环后执行,则需要将此代码放在回调中。这是改变:

app.post('/file', function(req, res) {
var fs = require('fs');
var file = req.files.file;
var source = fs.createReadStream(file.path);
var dest;

// destination directory
var dest_dir = './uploads;
var filename = file.name;

fs.readdir(dest_dir, function(err, dir_files) {
    for(var i = 0; i < dir_files.length; i++) {
        if(dir_files[i] == filename) {
            console.log("I can see this message, but the file isn't renamed");
            filename = filename + '_1'; // rename the file
            break;
        }
    }

    dest = fs.createWriteStream(dest_dir + '/' + filename);
    source.pipe(dest);

 });
 source.on('end', function() { res.json("File has been uploaded!") });
 source.on('error', function(err) { res.json("There was an error when attempting to upload this file.") });

});