[toc]node
建立時間:2019-08-12git
注意:在win10,v10.16.1 環境運行無問題github
首先引入相關包(會在使用處具體說明):api
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
複製代碼
這裏列出三種方式:promise
其中的同步或異步方法可酌情更改,實現代碼以下bash
/** * @param { copiedPath: String } (被複制文件的地址,相對地址) * @param { resultPath: String } (放置複製文件的地址,相對地址) */
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
方法,實現代碼以下koa
/** * @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);
}
}
複製代碼
如下代碼有引用,複製文件相關方法異步
使用了兩種方式:async
實現代碼和釋意以下:ui
/** * @des 參數解釋同上 */
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 方式一:利用子進程操做命令行方式 */
// 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 建立文件,使用流的形式能夠讀寫大文件 */
const readStream = fs.createReadStream(ccp)
const writeStream = fs.createWriteStream(crp)
readStream.pipe(writeStream)
} else {
try {
/** * @des 判斷讀(R_OK | W_OK)寫權限 */
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);
}
}
複製代碼
遞歸文件和文件夾,逐個刪除
實現代碼以下:
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);
}
}
複製代碼
|- index.js(主要執行代碼)
|- a
|- a.txt
|- b.txt
|- c
|- a.txt
|- b.txt
|- p
|- a.txt
|- b.txt
複製代碼
根據傳入的參數不一樣,執行相應的方法
/** * @des 獲取命令行傳遞的參數 */
const type = process.argv[2]
function execute() {
/** * @des 請根據不一樣的條件傳遞參數 */
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()
複製代碼
/** * @des 命令行傳參 * 執行 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相關方法的封裝,使用更簡單快捷
/** * @des fs-extra 包實現 * 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()
}
複製代碼
可執行源碼: github.com/NameHewei/n…
歡迎交流 Github