【发布时间】:2014-07-27 18:38:10
【问题描述】:
以下脚本在监视文件夹中是否有新的 .ogg 文件时运行良好。它成功地用新文件名创建了一个文件夹,然后根据文件的创建日期重命名文件/
但是,当我在脚本尝试创建一个已经存在的文件夹的同时添加多个文件时,就会出现问题,这表明它以某种方式混淆了两个文件名。有人对我可能做错了什么有任何建议吗?我认为它的代码结构很简单,尽管我无法弄清楚原因。
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');
});
}
【问题讨论】:
-
您是否希望两个文件都在同一个目录中(而您的代码没有这样做)?或者您希望每个文件有一个目录(因此当两个时间戳冲突时会出现问题)?
-
你应该使用同步调用。当
fs.exists的回调触发时,该文件可能不再存在。您可以使用fs.existsSync避免此问题。 (所有fs呼叫也是如此) -
差点忘了,但
fs.mkdir会被fs.watch接走。这可能会产生额外的问题,您应该根据event参数进行过滤。
标签: javascript node.js path fs