English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
The other day, while having lunch, I suddenly remembered that when I was taking the JS course at the New Great University, the teacher mentioned when talking about node that node can rename files in batches, so I thought about whether I could implement this feature.
After reading the official documentation of node, I found that the fs module has a readdir API, which reads the contents of a directory, tested it, and the returned result is an array, with the elements being the names of the folders. For more details, please refer to: https://www.oldtoolbag.com/article/58609.htm
There is also an API, rename, which is related to renaming. For more details, please refer to: https://www.oldtoolbag.com/article/58548.htm
Implementation idea
It's simple to organize the thoughts, just read the original file name into an array first, and then take the new name as an array, use renameAPI to implement it, but the names for batch renaming can only follow the number +1 I wrote the following function according to the rule
Example code
//rename.js const fs = require('fs') //Introduce the built-in file system of node function rename() { let newName = [] fs.readdir('.',/file/', (err, oldName) => { //Read the names of the files in the file folder, oldName is an array if (err) { console.log(err) } for (let i = 0; i < oldName.length; i++) { let name = `new${i}.jpg` // Take the picture as an example newName[i] = name // Assign the name to a new array } for (var i = 0; i < oldName.length; i++) { let oldPath = `./file/${oldName[i]}` //Original Path let newPath = `./file/${newName[i]}` //New Path fs.rename(oldPath, newPath, (err) => { //Rename if (err) { console.log(err) } console.log('done!') } } } } rename()
File Directory
Place the files 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, and there are still many shortcomings. Better methods are welcome for discussion.
Summary
That's all for this article. I hope the content of this article has certain reference value for everyone's learning or work. If you have any questions, you can leave a message for communication. Thank you for your support of the Yelling Tutorial.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.