Node fs rename problem

  node.js, question

Requirement: Rename all jpg files in a folder to 1.jpg, 2.jpg, 3.jpg, …, and so on.

Question 1: The fs module code using node is as follows:

var fs = require('fs');
 var counter = 1;
 Var re = /(.*) plus \.(jpg|bmp|gif|png)$/i;
 
 fs.readdir('./', function(err, files) {
 if (err) {
 Log ("failed");
 } else {
 for (var index = 0;   index < files.length;  Index plus)
 var element = files[index];
 if (re.test(element)) {
 Fs.rename(element,counter+jpg', function(err, fil) {
 if (err) {
 Log (counter plus' naming failure');
 } else {
 // console.log(files);
 Log (counter plus' named successfully');
 Counterplus;
 bracket
 })
 bracket
 
 bracket
 bracket
 })

Before operation:图片描述
After operation:图片描述
Excuse me: Why is only 1.jpg left? What is the problem?

Question 2: Do you know several ways to do this renaming? Shell, regular replace, python, etc. are all available. please give some code examples.

fs.renameIt is asynchronous, so there is no guarantee that the counter values are accumulated in sequence. The following writing method is recommended (tested on Windows).

fs.readdir('./', function(err, files) {
 if (err) {
 Log ("failed");
 return;  //If the error is returned directly, else is not needed.
 bracket
 Files. foreach (fn) {//is easier
 if(!  re.test(fn)) return;
 Log ("> > plus fn);
 Fs.renameSync(fn,counter plus'. jpg');  //Synchronize rename
 Counterplus;
 });
 });