0

I am trying to rename the directories if it contains space in their name. It's renaming properly but after renaming call back function defined never called.

my recursive function in below, where fs for file system and complete-directory-tree.

function renameDir(dirs){
    dirs.forEach(function(e){

        if(e.name.match(/\s+/g)){
            var cname = e.name.replace(/\s+/g,'_');
            var cpath = e.path.replace(e.name,cname);
            fs.rename(e.path,cpath,function(err,data){
                if(err) console.log(err)
                else{
                    console.log('success');
                    e.path = cpath;
                    e.name = cname;   
                }
            });
        }

        var nested = cDT(e.path)
        if( nested.children && (nested.children.length > 0) ) renameDir(nested.children);
    });
}
OutForCode
  • 189
  • 15
  • It runs asynchronously, so any code you have which looks at the values in `dirs` after you call `renameDir` will run *before* the callbacks have run. – Quentin Oct 30 '18 at 07:55
  • @Quentin, yeah i tried only `console.log('success')`, even. But It looks like it never logged. Still all the directories renamed perfectly. – OutForCode Oct 30 '18 at 07:57
  • @Quentin please try at your end and let me know. And please mind EVEN I TRIED WITH CONSOLE.LOG ALONE , BUT IT'S NOT LOGGING IT IN CONSOLE, BUT THE OPERATION / RENAMING PROCESS SUCCESSFUL. And I am using `fs.rename` not `fs.renameSync` – OutForCode Oct 30 '18 at 08:02

1 Answers1

1

Use this code and path should be depend on your folder structure

'use strict';
const [fs, path] = [require('fs'), require('path')];

fs.readdir(__dirname, (err, data) => {
data.map(d => {
    if (d.includes(' ')) {
        let name = d.replace(/ /g, '_');
        fs.renameSync(path.resolve(__dirname, d), path.resolve(__dirname, name));
    }
})});
Biplab Malakar
  • 645
  • 6
  • 10