nodejs更改資料夾下的檔名
阿新 • • 發佈:2018-12-26
將檔案下的“0001.jpg,0002.jpg,0003.jpg….”改為“0.jpg,1.jpg,2.jpg…”格式
採用同步的方式遍歷,一般用非同步方式。
var fs = require('fs');
var fileDirectory = "d:\\coorsjson";
var newfileDirectory = "d:\\newname";
if (fs.existsSync(fileDirectory)) {
var files = fs.readdirSync(fileDirectory);
for (var i = 0; i < files.length; i++) {
var filePath = fileDirectory + "/" + files[i];
var name = parseInt(files[i].slice(0, -4), 10) - 1;
console.log(name);
var fileName = name.toString() + ".jpg";
var newFilePath = newfileDirectory + "/" + fileName;
fs.rename(filePath, newFilePath, function(err) {
if (err) throw err;
console.log(fileName + ' ok~');
});
}
} else {
console.log(fileDirectory + " Not Found!");
}