// 為什么會有這個東西,因為用百度雲下載了很多視頻,不知道為什么存在很多 .downloading的文件,所以就有了這段代碼,還有就是文件名帶了很多沒用的信息,想把無用信息剔除掉就有了后面的一段代碼
/** * 刪除目錄下 指定 文件方法 * 參數: dir 文件夾名稱 * fs.stat => 判斷是文件還是文件夾 * fs.unlink => 刪除文件 * fs.readdir => 讀取文件夾內容 */ const fs = require('fs') const path = require('path') const deleteFiles = function (dir) { fs.readdir(dir, function (err, files) { files.forEach(function (filename) { var src = path.join(dir, filename) fs.stat(src, function (err, st) { if (err) { throw err } // 判斷是否為文件 if (st.isFile()) { // 這里可以使用正則,也可以使用其他方法,比如字符串處理等,/\.d\.ts$/ if (/\.we$/.test(filename)) { fs.unlink(src, err => { if (err) throw err console.log('成功刪除:' + src) }) } } else { // 遞歸文件夾 deleteFiles(src) } }) }) }) } deleteFiles('./')
修改文件名稱
fs = require('fs') // 引用文件系統模塊 const PATH = `./src/` // 當前文件夾 const readFileList = function (path, filesList) { filesList = filesList || [] let files = fs.readdirSync(path) files.forEach(function (filename, index) { // const stat = fs.statSync(path + filename); //讀取的文件信息 // isDirectory 判斷是不是目錄 if (fs.statSync(path + filename).isDirectory()) { // 遞歸讀取文件 readFileList(`${path}${filename}/`, filesList) } else { filesList.push({ path, // 路徑 filename // 名字 }) } }) return filesList } // 修改文件名稱 const rename = function (oldPath, newPath, filename, newSuffixFile) { fs.rename(oldPath, newPath, function (err) { if (err) { throw err } console.log(`${filename} 修改為 => ${newSuffixFile}`) }) } // 批量修改文件名稱 const getChangeFiles = function (path, oldSuffix, newSuffix) { if (!oldSuffix && !newSuffix) { console.log(`后綴未設置`) } this.readFileList(path).forEach(item => { if (item.filename.indexOf(oldSuffix) > -1) { console.log(item.filename) let oldPath = item.path + item.filename, newSuffixFile = item.filename.split(oldSuffix)[0] + newSuffix, newPath = item.path + newSuffixFile rename(oldPath, newPath, item.filename, newSuffixFile) } }) } getChangeFiles(PATH, `.we`, `.js`)
// 引入fs文件處理模塊
const fs = require('fs')
// 現在我們要關心的是‘icons‘文件夾
// 我們不妨用變量表示這個文件夾名稱,方便日后維護和管理
const src = 'dist'
// API文檔中中找到遍歷文件夾的API
// 找到了,是fs.readdir(path, callback)
// 文檔中有敘述:
// 讀取 path 路徑所在目錄的內容。 回調函數 (callback) 接受兩個參數 (err, files) 其中 files 是一個存儲目錄中所包含的文件名稱的數組
// 因此:
fs.readdir(src, function (err, files) {
// files是名稱數組,因此
// 可以使用forEach遍歷哈, 此處為ES5 JS一點知識
// 如果不清楚,也可以使用for循環哈
files.forEach(function (filename) {
// 下面就是文件名稱重命名
// API文檔中找到重命名的API,如下
// fs.rename(oldPath, newPath, callback)
// 下面,我們就可以依葫蘆畫瓢,確定新舊文件名稱:
const oldPath = src + '/' + filename
// newPath = src + ‘/‘ + filename.replace(/_/g, ‘-‘);
const newPath = src + '/' + 'index.html'
if (filename === 'Homepad.html') {
// 重命名走起
fs.rename(oldPath, newPath, function (err) {
if (!err) {
console.log(filename + '重命名成功!')
}
})
}
})
})