The fs.mkdir file directory is added

Use case

  • Step by step new directories will successfully print success
Fs.mkdir ("a", function (err) {if (err) {console.log(err); if (err) {console.log(err); return; } console.log("success..." ); //success });Copy the code
  • Error adding a new directory across levels in a directory that does not exist! Node’s built-in module does not support creating new directories from non-existing directories (that’s what I’m going to do).

An enhanced version of fs.mkdir

A recursive version

  • Train of thought
  1. The path to be added is sliced according to “/” to generate array cache
  2. Index initial value = 1; Slice (0, index) and join(‘/’) to form path string currentPath
  3. Fs.stat is used to describe the status of the file. If no file exists, an error occurs
  4. Fs.mkdir (currentPath, recursively calling itself) was called in error last day;
  5. The file exists by calling itself
  • Code implementation
function mkdir(pathStr, cb) { let pathList = pathStr.split("/"); // call fs.mkdir let index = 1; function make(err) { if (err) return cb(err); if (index === pathList.length + 1) return cb(); // Each call will use the last generated file name as the next target file, Slice (0, index) join('/') string let currentPath = pathList. Slice (0, index) index++).join("/"); // console.log("pathList.slice(0,index)", pathList.slice(0, index)); fs.stat(currentPath, function (err) { if (err) { fs.mkdir(currentPath, make); console.log({ currentPath }); // If not, create fs.mkdir(currentPath, make); } else { make(); }}); } make(); }Copy the code
  • test
  1. No errors are reported at this point
mkdir("a/b/c/d", function (err) { if (err) console.log(err); console.log("success..." ); });Copy the code
  • Printing effect

For loop +await version

  • Implementation approach
  1. Take ‘/’ as the benchmark to cut the path for the corresponding array, the array for loop traversal
  2. ExistsSync () in the for loop synchronizes the existence of the directory.

Return true if the directory exists, false if the directory does not exist 3. Does not exist the fs. Mkdir (currentPath)

  • The implementation code
const fs = require("fs").promises; // promises const {existsSync} = require("fs"); // Promises const {existsSync} = require("fs"); async function mkdir(pathStr, cb) { let pathList = pathStr.split("/"); for (let i = 1; i <= pathList.length; i++) { let currentPath = pathList.slice(0, i).join("/"); if (! existsSync(currentPath)) { await fs.mkdir(currentPath); }}}Copy the code
  • Calls will recursively call tiled then chain calls
The mkdir (" a/b/c/d "), then (() = > {the console. The log (" create success "); }) .catch((err) => { console.log(err); });Copy the code
  • Printing effect

The fs.rmdir file directory was deleted

Use case

  • Delete fs.rmdir directly for directories with subdirectories
const fs = require("fs"); const path = require("path"); fs.rmdir("a", function (err) { console.log(err); });Copy the code
  • Usage result (error)

Fs. Rmdir enhanced

Serial version

  • Train of thought
  1. Fs. stat returns the following information about the file: file status Information about the file, modification time, creation time, and directory status. The second argument to the fs.stat callback is to get the file object, using the isFile, isDirectory methods

  2. IsFile direct fs.unlink(dir, cb); Delete current file

  3. IsDirectory calls fs.readdir to return an array of subdirectories

  4. Join path.join(dir, item))

  5. Recursively call itself in turn on the concatenated path array

  6. Delete all subdirectories after deleting itself

  • Code implementation
function rmdir(dir, cb) { fs.stat(dir, function (err, If (statobj.isdirectory ()) {// 1.1 read directory fs.readdir callback function can get the result of read directory Fs. readdir(dir, function (err, dirs) { Dirs = dirs.map((item) => path.join(dir, item)); Let index = 0; // Let index = 0; If (index === dirs.length) return fs.rmdir(dir, cb); if (index === dirs.length) return fs.rmdir(dir, cb); Rmdir (dirs[index++], step) if index== dirs.length; } step(); }); } else {// 1.2 dir is to delete files directly with fs.unlink fs.unlink(dir, cb); }}); }Copy the code
  • test
Rmdir ("a", function () {console.log(" delete succeeded "); });Copy the code
  • The execution result

The parallel version

  • Code implementation
const fs = require("fs").promises; const path = require("path"); async function rmdir(dir) { let statObj = await fs.stat(dir); if (statObj.isDirectory) { let dirs = await fs.readdir(dir); await Promise.all(dirs.map((item) => rmdir(path.join(dir, item)))); await fs.rmdir(dir); } else { return fs.unlink(dir); }}Copy the code
  • call
Rmdir ("a").then(() => {console.log(" parallel delete succeeded "); });Copy the code
  • The execution result

The difference between parallel and serial

Serial is understood as a single thread that can only execute the next parallel asynchronous execution based on the fact that the previous execution has finished without any dependence on each other so that the latter is more efficient than the former

The operational nature of a file directory

  1. File directory nature: is a tree structure of data
  2. File directory operations are operations on data in a tree structure
  3. Leave a hole for next time to write tree structure understanding

Finally, if you find this article helpful, please remember to like three times oh, thank you very much