How to use Node.js rename files in folder All In One
How to use Node.js rename files in folder All In One
rename
fs.rename
fs.rename(oldPath, newPath, callback)
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
https://nodejs.org/api/fs.html#fsrenameoldpath-newpath-callback
fs.renameSync
fs.renameSync(oldPath, newPath)
https://nodejs.org/api/fs.html#fsrenamesyncoldpath-newpath
fsPromises.rename
fsPromises.rename(oldPath, newPath)
https://nodejs.org/api/fs.html#fspromisesrenameoldpath-newpath
demos
替换和删除文件名中的
中文字符
/半脚字符
/全脚字符
// import * as pfs from "node:fs/promises";
import fs from 'node:fs';
import path from 'node:path';
const __dirname = path.resolve();
// const __filename = fileURLToPath(import.meta.url);
// console.log(`__dirname`, __dirname);
const folder = path.join(__dirname, '深入浅出搞定 React');
const files = fs.readdirSync(folder);
// console.log(`files`, files);
for (const file of files) {
// const filename = file.replaceAll(/(:)/g, ``).replace(/(/, `(`).replace(/)/, `)`).replace(`?`, ``);
const filename = file
.replace(/:/g, `:`)
.replace(/(/, `(`)
.replace(/)/, `)`)
.replace(/,/, `,`)
.replace(/(“|”)/g, `"`)
.replace(`?`, ``);
fs.renameSync(`${folder}/${file}`, `${folder}/${filename}`, (err) => {
if(err) {
console.error(`rename ❌`, err);
}
console.log(`rename ✅`)
}
)
}
const fs = require('fs')
const files = fs.readdirSync(__dirname)
for (const file of files) {
if (file.endsWith('.md')) {
fs.mkdirSync(
__dirname + '/' + file.replace('.md', ''),
{ recursive: true },
(err) => {
console.log(err)
}
)
fs.renameSync(
__dirname + '/' + file,
__dirname + '/' + file.replace('.md', '') + '/index.md',
(err) => {
console.log(err)
}
)
}
}
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://flaviocopes.com/node-mass-rename-files/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17703463.html
未经授权禁止转载,违者必究!