Home >Web Front-end >JS Tutorial >How to use node to implement a function for batch renaming files
This article mainly introduces you to the relevant information about using node to implement a function of batch renaming files. The article introduces it in detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s learn with the editor below.
Implementation ideas
After sorting out the idea, it is very simple. First, read the file name of the original file and put it into an array, and then use the renameAPI to implement the new name as an array. However, The names for batch renaming can only follow the rule of number + 1. The following function is written
Sample code
//rename.js const fs = require('fs') //引入node内置的文件系统 function rename() { let newName = [] fs.readdir('./file/', (err, oldName) => { //读取file文件夹下的文件的名字,oldName是一个数组 if (err) { console.log(err) } for (let i = 0; i < oldName.length; i++) { let name = `new${i}.jpg` // 以图片为例 newName[i] = name // 把名字赋给一个新的数组 } for (var i = 0; i < oldName.length; i++) { let oldPath = `./file/${oldName[i]}` //原本的路径 let newPath = `./file/${newName[i]}` //新路径 fs.rename(oldPath, newPath, (err) => { //重命名 if (err) { console.log(err) } console.log('done!') }) } }) } rename()
File directory
Place the file to be renamed in the file folder
Open the terminal, cd to the rename folder, and execute node rename.js
This is just a simple implementation, or There are many deficiencies, there are better methods, welcome to discuss
Related recommendations:
Introduction to the implementation method of batch renaming all files in a folder in PHP
Python method to batch rename files in a specified directory
The above is the detailed content of How to use node to implement a function for batch renaming files. For more information, please follow other related articles on the PHP Chinese website!