node刪除、復(fù)制文件或文件夾示例代碼
注意:在win10,v10.16.1 環(huán)境運(yùn)行無問題
首先引入相關(guān)包(會在使用處具體說明):
const fs = require('fs') const path = require('path') const child_process = require('child_process') const fsEx = require('fs-extra') /** * @des 該包為實驗性API */ const fsPromises = require('fs').promises
對文件的操作
復(fù)制文件
這里列出三種方式:
- 使用 writeFileSync 和 readFileSync 結(jié)合
- 使用 copyFileSync
- 使用promises的copyFile方法
其中的同步或異步方法可酌情更改,實現(xiàn)代碼如下
/** * @param { copiedPath: String } (被復(fù)制文件的地址,相對地址) * @param { resultPath: String } (放置復(fù)制文件的地址,相對地址) */ function copyFile(copiedPath, resultPath) { copiedPath = path.join(__dirname, copiedPath) resultPath = path.join(__dirname, resultPath) try { /** * @des 方式一 */ // fs.writeFileSync(resultPath, fs.readFileSync(copiedPath)) /** * @des 方式二 */ // fs.copyFileSync(copiedPath, resultPath) console.log('success'); } catch (error) { console.log(error); } /** * @des 方式三 */ fsPromises.copyFile(copiedPath, resultPath) .then(() => { console.log('success'); }).catch((err) => { console.log(err); }); }
刪除文件
使用 unlinkSync 方法,實現(xiàn)代碼如下
/** * @param { delPath:String } (需要刪除文件的地址) * @param { direct:Boolean } (是否需要處理地址) */ function deleteFile(delPath, direct) { delPath = direct ? delPath : path.join(__dirname, delPath) try { /** * @des 判斷文件或文件夾是否存在 */ if (fs.existsSync(delPath)) { fs.unlinkSync(delPath); } else { console.log('inexistence path:', delPath); } } catch (error) { console.log('del error', error); } }
對文件夾(目錄)的操作
以下代碼有引用,復(fù)制文件相關(guān)方法
復(fù)制文件夾
使用了兩種方式:
- child_process
- 遞歸的讀取文件和文件夾再在指定地址創(chuàng)建
實現(xiàn)代碼和釋意如下:
/** * @des 參數(shù)解釋同上 */ function copyFolder(copiedPath, resultPath, direct) { if(!direct) { copiedPath = path.join(__dirname, copiedPath) resultPath = path.join(__dirname, resultPath) } function createDir (dirPath) { fs.mkdirSync(dirPath) } if (fs.existsSync(copiedPath)) { createDir(resultPath) /** * @des 方式一:利用子進(jìn)程操作命令行方式 */ // child_process.spawn('cp', ['-r', copiedPath, resultPath]) /** * @des 方式二: */ const files = fs.readdirSync(copiedPath, { withFileTypes: true }); for (let i = 0; i < files.length; i++) { const cf = files[i] const ccp = path.join(copiedPath, cf.name) const crp = path.join(resultPath, cf.name) if (cf.isFile()) { /** * @des 創(chuàng)建文件,使用流的形式可以讀寫大文件 */ const readStream = fs.createReadStream(ccp) const writeStream = fs.createWriteStream(crp) readStream.pipe(writeStream) } else { try { /** * @des 判斷讀(R_OK | W_OK)寫權(quán)限 */ fs.accessSync(path.join(crp, '..'), fs.constants.W_OK) copyFolder(ccp, crp, true) } catch (error) { console.log('folder write error:', error); } } } } else { console.log('do not exist path: ', copiedPath); } }
刪除文件夾
遞歸文件和文件夾,逐個刪除
實現(xiàn)代碼如下:
function deleteFolder(delPath) { delPath = path.join(__dirname, delPath) try { if (fs.existsSync(delPath)) { const delFn = function (address) { const files = fs.readdirSync(address) for (let i = 0; i < files.length; i++) { const dirPath = path.join(address, files[i]) if (fs.statSync(dirPath).isDirectory()) { delFn(dirPath) } else { deleteFile(dirPath, true) } } /** * @des 只能刪空文件夾 */ fs.rmdirSync(address); } delFn(delPath); } else { console.log('do not exist: ', delPath); } } catch (error) { console.log('del folder error', error); } }
執(zhí)行示例
目錄結(jié)構(gòu)
|- index.js(主要執(zhí)行代碼)
|- a
|- a.txt
|- b.txt
|- c
|- a.txt
|- b.txt
|- p
|- a.txt
|- b.txt
根據(jù)傳入的參數(shù)不同,執(zhí)行相應(yīng)的方法
/** * @des 獲取命令行傳遞的參數(shù) */ const type = process.argv[2] function execute() { /** * @des 請根據(jù)不同的條件傳遞參數(shù) */ if (type === 'copyFile') { copyFile('./p/a.txt', './c/k.txt') } if (type === 'copyFolder') { copyFolder('./p', './a') } if (type === 'delFile') { deleteFile('./c/ss.txt') } if (type === 'delFolder') { deleteFolder('./a') } } execute()
命令行傳參數(shù)
/** * @des 命令行傳參 * 執(zhí)行 node ./xxx/index.js 111 222 * 輸出: * 0: C:\Program Files\nodejs\node.exe * 1: G:\GitHub\xxx\xxxx\index.js * 2: 111 * 3: 222 */ process.argv.forEach((val, index) => { console.log(`${index}: ${val}`); });
利用 fs-extra 實現(xiàn)
這是對fs相關(guān)方法的封裝,使用更簡單快捷
/** * @des fs-extra 包實現(xiàn) * api參考: https://github.com/jprichardson/node-fs-extra */ function fsExtra() { async function copy() { try { await fsEx.copy(path.join(__dirname + '/p'), path.join(__dirname + '/d')) console.log('success'); } catch (error) { console.log(error); } } copy() }
可執(zhí)行源碼: github.com/NameHewei/n…
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
Nodejs在局域網(wǎng)配置https訪問的實現(xiàn)方法
做一個局域網(wǎng)WebRTC視頻聊天系統(tǒng),需要用到HTTPS。因此,配置Node.js使其支持HTTPS訪問。這篇文章主要介紹了Nodejs在局域網(wǎng)配置https訪問的實現(xiàn)方法,需要的朋友可以參考下2020-10-10node基于async/await對mysql進(jìn)行封裝
這篇文章主要介紹了node基于async/await對mysql進(jìn)行封裝,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,,需要的朋友可以參考下2019-06-06node.js+jQuery實現(xiàn)用戶登錄注冊AJAX交互
本篇文章主要介紹了用Node.js當(dāng)作后臺、jQuery寫前臺AJAX代碼實現(xiàn)用戶登錄和注冊的功能的相關(guān)知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04node+axios實現(xiàn)下載外網(wǎng)文件到本地
這篇文章主要為大家介紹了node+axios實現(xiàn)下載外網(wǎng)文件到本地示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06Nest.js Controller路由和請求處理強(qiáng)大功能解析
這篇文章主要為大家,介紹了Nest.js Controller路由和請求處理強(qiáng)大功能解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12iOS + node.js使用Socket.IO框架進(jìn)行實時通信示例
本篇文章主要介紹了iOS + node.js使用Socket.IO框架進(jìn)行實時通信示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04node pnpm修改默認(rèn)包的存儲路徑(操作方法)
PNPM是一個新的包管理工具,也是NPM的另一個替代方案,與NPM不同,PNPM使用符號鏈接(symlink)而不是復(fù)制文件來安裝包,這篇文章主要介紹了node pnpm修改默認(rèn)包的存儲路徑,需要的朋友可以參考下2024-05-05