node.js批量修改文件名
时间: 2024-03-04 13:46:59 浏览: 86
在Node.js中,可以使用fs模块来批量修改文件名。下面是一个简单的示例代码:
```javascript
const fs = require('fs');
const path = require('path');
// 定义要修改的文件夹路径
const folderPath = '/path/to/folder';
// 读取文件夹中的所有文件
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('读取文件夹失败:', err);
return;
}
// 遍历每个文件
files.forEach((file) => {
// 构建旧文件路径和新文件路径
const oldFilePath = path.join(folderPath, file);
const newFilePath = path.join(folderPath, 'new_' + file);
// 修改文件名
fs.rename(oldFilePath, newFilePath, (err) => {
if (err) {
console.error(`修改文件名失败: ${oldFilePath}`, err);
} else {
console.log(`成功修改文件名: ${oldFilePath} -> ${newFilePath}`);
}
});
});
});
```
上述代码会将指定文件夹中的所有文件名前面添加"new_"前缀。你可以根据实际需求修改代码来实现其他的批量修改文件名的操作。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)