I learn how to use Node and Ecmascript 6.
The aim of my script is to rename a list of png files in a directory. I want to rename only the png files (let'say there is jpg too) and display at the end the number of files renamed. Due to non-blocking nature of Node, it's not so obvious and i decided to take advantage of the opportunity to discover ES6 promise.
'use strict';
const fs = require('fs-extra');
const dir = '/Users/toto/Desktop/png/';
const suffix = '_IMAGE.';
const regex = /(.*)\.(png)$/;
var nbFiles = 0;
// Rename a png file with a suffix
var renameFile = (filename) => {
return new Promise((resolve, reject) => {
if(regex.test(filename)){
let newFileName = filename.replace(regex, '$1' + suffix + '$2');
fs.rename(dir + filename, dir + newFileName, (err) => {
let msg = filename + ' => ' + newFileName;
if (err) {
console.log('KO : rename of ' + msg);
reject(err);
}
console.log('OK : rename of ' + msg);
resolve(nbFiles++);
});
}
});
};
// Read files in a directory and call renameFile + display number of files renamed
fs.readdir(dir, (err, files) => {
if(err) return console.error(err);
var promise = Promise.all(
files.map(renameFile)
).then(function(nb){
console.log('Number of files renamed : ', nb);
}).catch(function(err){
console.log('Error ', err);
});
});
The expected result is to get files renamed and to see the message Number of files renamed.
I get files renamed but i can't see any message (of the then or the catch call). Something is wrong somewhere but debug sessions can't help me.
Thanks for any help!
PS : my environment is Node 5.10 and OS X 10.11.