A brief discussion on fs.mkdir and fs.rmdir in Nodejs file module
This article will take you through Nodejs file operations fs.mkdir and fs.rmdir. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
[Recommended study: "nodejs Tutorial"]
Fs.mkdir file directory is newly added
Case usage
- Added directories level by level will successfully print success
fs.mkdir("a", function (err) { // 当a不存在的时候直接创建 a/b会报错 if (err) { console.log(err); return; } console.log("success...");//success });
- Cross-level directories that do not exist An error occurred when adding a directory under the directory! ! , the built-in module of node itself does not support adding new directories under non-existing directories (this is what I want to do)
fs. Enhanced version of mkdir
Recursive version
Idea
According to "/ "Carry out cutting to generate array cache
index initial value = 1; perform slice(0, index) on the array corresponding to the path in sequence, intercept and join('/') into the path string currentPath
fs.stat is used to describe the status of the file. If the file does not exist, an error occurs
An error occurred the previous day and called fs.mkdir( currentPath, call yourself recursively);
The file exists and call yourself
Code implementation
function mkdir(pathStr, cb) { let pathList = pathStr.split("/"); // 递归调用fs.mkdir let index = 1; function make(err) { if (err) return cb(err); if (index === pathList.length + 1) return cb(); //每次 调用要将上次的已经生成的文件名做下次的目标文件, // 所以 slice(0, index) 第二参数也要 累加 //slice(0, index) 截取后join('/') 成字符串 let currentPath = pathList.slice(0, 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 }); // 如果不存在,再创建 fs.mkdir(currentPath, make); } else { make(); } }); } make(); }
Test:
No error is reported at this time
mkdir("a/b/c/d", function (err) { if (err) console.log(err); console.log("success..."); });
Print effect
##for loop await version
Implementation ideas- Use '/' as the basis to cut the path into the corresponding array, and traverse the array in a for loop
- existsSync() in the for loop uses a synchronous method to detect whether the directory exists.
const fs = require("fs").promises; //node11后可以直接.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); } } }The call will recursively call the tile then chain call
mkdir("a/b/c/d") .then(() => { console.log("创建成功"); }) .catch((err) => { console.log(err); });Print effect
Case usage
Delete fs.rmdir directly in directories with subdirectories
const fs = require("fs"); const path = require("path"); fs.rmdir("a", function (err) { console.log(err);//会报错 });
Use results (error report)
Serial version
Thinking
- fs.stat will return the specific information of the file: the status of the file Information, modification time, creation time, directory status; the second parameter in the callback of fs.stat is to obtain the file object, the object method: isFile, isDirectory
- ##isFile directly fs.unlink (dir, cb); Delete the current file
- isDirectory calls fs.readdir to return an array of subdirectories
- Map the subdirectory array Traverse & parent file name, child file name, splice path.join(dir, item))
- Recursively call yourself on the spliced path array in turn
-
-
##Code implementation
function rmdir(dir, cb) { fs.stat(dir, function (err, statObj) { // 1:判断dir的文件信息 statObj 是目录还是 文件 if (statObj.isDirectory()) { // 1.1 读取文件夹fs.readdir 回调函数 里可以拿到文件夹读取结果 fs.readdir(dir, function (err, dirs) { // 遍历 文件夹中文件,path 拼接 父文件名称+ 子文件名称 dirs = dirs.map((item) => path.join(dir, item)); // 把目录里面 的拿出来,一个删除后 删除下一个 let index = 0; function step() { // 将子文件都删除完后,删除自己 if (index === dirs.length) return fs.rmdir(dir, cb); //删除第一个成功后 继续调用rmdir 删除下一个子文件,直到index===dirs.length 时 删除自己 rmdir(dirs[index++], step); } step(); }); } else { // 1.2 dir是文件 直接删除 用fs.unlink fs.unlink(dir, cb); } }); }
Test
rmdir("a", function () { console.log("删除成功"); });
Execution result
Parallel version
Code implementationconst 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);
}
}
Call
rmdir("a").then(() => { console.log("并行删除成功"); });
Execution result
The difference between parallel and serial
Serial is understood to mean that a single thread can only execute the next one after the previous execution is completed. Parallel, asynchronous execution, no dependencies on each other Then the latter will be more efficient than the former
The operating essence of the file directoryThe essence of the file directory: it is tree-structured data
The operation of the file directory is the operation of the tree structure data
-
Leave a hole for writing next time
Tree structure Understanding
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of A brief discussion on fs.mkdir and fs.rmdir in Nodejs file module. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor