简体   繁体   中英

Using node.js how to rename all files from a folder

I have a folder with multiple files for ex. files with name old.html , old.txt , old.json and i want to rename all these files to new.html , new.txt , new.json. Is there any method present in node js which i can use here?

This is what you are looking for:

const { join, extname, basename } = require('path');
const { readdirSync, renameSync } = require('fs');

for (const oldFile of readdirSync(pathToOldFolder)) {
    const extension = extname(oldFile);
    const name = basename(oldFile, extension);
    if (name === 'old') {
        renameSync(join(pathToOldFolder, oldFile), join(pathToOldFolder, 'new' + extension));
    }
}

You could use the FS module?

Use the following to retrieve a list of files

fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
});

then loop over them to rename the files

fs.rename('oldFile.txt', 'newFile.txt', (err) => {
  if (err) throw err;
  console.log('Rename complete!');
});

check here , though it may not fulfil your requirement

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

like { file1: old.txt, file2: old.html, ... ... ... }

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p].split(".")[0] + obj[p].split(".")[1], '/path/to/' + 'new' + obj[p].split(".")[1], function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM