[toc]
Creation time: 2019-08-12
Note: In Windows 10, v10.16.1 runs without problems
First, introduce related packages (detailed in use) :
const fs = require('fs')
const path = require('path')
const child_process = require('child_process')
const fsEx = require('fs-extra')
/** * @des This package is experimental API */
const fsPromises = require('fs').promises
Copy the code
Operations on files
Copy the file
Here are three ways:
- Use both writeFileSync and readFileSync
- Using copyFileSync
- Use Promises’ copyFile method
The synchronous or asynchronous methods can be changed as appropriate, and the implementation code is as follows
/** * @param {copiedPath: String} (address of the copied file, relative address) * @param {resultPath: String} (address of the copied file, relative address) */
function copyFile(copiedPath, resultPath) {
copiedPath = path.join(__dirname, copiedPath)
resultPath = path.join(__dirname, resultPath)
try {
/** * @des mode one */
// fs.writeFileSync(resultPath, fs.readFileSync(copiedPath))
/** * @des mode 2 */
// fs.copyFileSync(copiedPath, resultPath)
console.log('success');
} catch (error) {
console.log(error);
}
/** * @des mode three */
fsPromises.copyFile(copiedPath, resultPath)
.then((a)= > {
console.log('success');
}).catch((err) = > {
console.log(err);
});
}
Copy the code
Delete the file
Using the unlinkSync method, the implementation code is as follows
/** * @param {delPath: String} (address to delete file) * @param {direct: Boolean} (address to process) */
function deleteFile(delPath, direct) {
delPath = direct ? delPath : path.join(__dirname, delPath)
try {
/** * @des Checks whether a file or folder exists */
if (fs.existsSync(delPath)) {
fs.unlinkSync(delPath);
} else {
console.log('the inexistence path:', delPath); }}catch (error) {
console.log('del error', error); }}Copy the code
Operations on folders (directories)
The following code has reference, copy file related methods
Copy folder
Two approaches are used:
- child_process
- Recursively read files and folders and then create them at the specified address
The implementation code and interpretation are as follows:
/** * @des The same as the preceding */
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 mode 1: Use a subprocess to operate the command line */
// child_process.spawn('cp', ['-r', copiedPath, resultPath])
/** * @des Mode 2: */
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 create file, use stream form can read and write large file */
const readStream = fs.createReadStream(ccp)
const writeStream = fs.createWriteStream(crp)
readStream.pipe(writeStream)
} else {
try {
/ * * * @ des judge read (R_OK | W_OK) write permissions * /
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); }}Copy the code
Delete folders
Recursive files and folders, deleted one by one
The implementation code is as follows:
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 can only delete empty folders */
fs.rmdirSync(address);
}
delFn(delPath);
} else {
console.log('do not exist: ', delPath); }}catch (error) {
console.log('del folder error', error); }}Copy the code
Execute the sample
The directory structure
| - index. Js (main execution code) | | - a - a.t xt | - b.t xt | | - c - a.t xt | - b.t xt | - p | - a.t xt | - b.t xtCopy the code
Depending on the parameters passed in, the corresponding method is executed
/** * @des gets the argument */ passed from the command line
const type = process.argv[2]
function execute() {
/** * @des Please pass parameters */ according to different conditions
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()
Copy the code
Command line pass parameters
* 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}`);
});
Copy the code
Using FS-extra
This is an encapsulation of fS-related methods and is easier and faster to use
/ * * * @ des fs - extra package implementation * API reference: 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()
}
Copy the code
Executable source code: github.com/NameHewei/n…
Welcome to Github