下面的脚本在为新的.ogg文件监视文件夹时发挥了巨大的作用。它成功创建一个新文件名的文件夹,然后根据文件根据其创建日期重命名文件/当同时添加2时重命名文件失败
然而,当我在脚本尝试创建文件夹的同时添加多个文件时出现问题已经存在,表明它以某种方式混合了这两个文件名。有没有人有任何建议,我可能会做错吗?我认为它的简单代码结构虽然我无法解决原因。
var baseDir = './',
path = require('path'),
fs = require('fs');
// watch the directory for new files
fs.watch(baseDir, function(event, file) {
var ext = path.extname(file)
basename = path.basename(file).substring(0, path.basename(file).length - ext.length);
// check it wasnt a delete action
fs.exists(baseDir + file, function(exists) {
// check we have the right file type
if(exists && ext === '.ogg'){
// get the created date
fs.stat(baseDir + file, function (err, stats){
if (err)
throw err;
var year = stats.ctime.getFullYear();
var month = stats.ctime.getMonth()+1;
var day = stats.ctime.getDate();
var hour = stats.ctime.getHours();
var sec = stats.ctime.getSeconds();
if(month < 10){
month = '0' + month;
}
if(day < 10){
day = '0' + day;
}
if(hour < 10){
hour = '0' + hour;
}
if(sec < 10){
sec = '0' + sec;
}
var name = year + '' + month + '' + day + '' + hour + '' + sec;
// does the basename directory exist?
fs.exists(baseDir + '/' + basename, function(exists) {
// if the directory doesnt exist
if(!exists){
// make the directory
fs.mkdir(baseDir + '/' + basename, 0777, function (err, stats){
if (err)
throw err;
moveFile(file, basename, name, ext);
});
} else {
moveFile(file, basename, name, ext);
}
});
});
}
});
});
function moveFile(file, basename, name, ext){
// move the file to the new directory
fs.rename(baseDir + file, baseDir + '/' + basename + '/' + name + ext, function (err) {
if (err)
throw err;
// console.log('Rename complete');
});
}
你想这两个文件在同一目录中结束(和你的代码不这样做)?或者你想每个文件都有一个目录(并且在两个时间戳发生冲突时有问题)? – pixelistik
你应该使用同步调用。当'fs.exists'的回调触发时,文件可能不再存在。你可以用'fs.existsSync'来避免这个问题。 (所有'fs'调用也是如此) –
几乎忘记了,但是'fs.mkdir'会被'fs.watch'选中。这可能会产生额外的问题,您应该根据'event'参数进行过滤。 –