57 # 目录操作

简介: 57 # 目录操作

同步创建文件夹

const fs = require("fs");
fs.mkdirSync("a");

创建目录得保证父路径存在

fs.mkdirSync("a/b");

不然会报错

下面实现没有父路径存在也能创建成功的方法

同步方法:

function mkdirSyncP(paths) {
    let arr = paths.split("/");
    for (let i = 0; i < arr.length; i++) {
        let currentPath = arr.slice(0, i + 1).join("/");
        console.log("mkdirSyncP---currentPath---->", currentPath);
        // 如果文件夹不存在就创建
        if (!fs.existsSync(currentPath)) {
            fs.mkdirSync(currentPath);
        }
    }
}
mkdirSyncP("a/b/c/d/e");

异步方法:不会阻塞主线程

function mkdirP(paths, cb) {
    let arr = paths.split("/");
    let index = 0;
    function next() {
        // 如果路径不存在就停止创建
        if (index === arr.length) return cb();
        let currentPath = arr.slice(0, ++index).join("/");
        // fs.exists 被废弃,可以使用 fs.access 替代
        console.log("mkdirP---currentPath---->", currentPath);
        fs.access(currentPath, (err) => {
            // 没有文件夹就报错,报错就异步创建,不报错就 next
            if (err) {
                fs.mkdir(currentPath, next);
            } else {
                next();
            }
        });
    }
    next();
}
mkdirP("b/c/d/e/f/g", () => {
    console.log("异步创建成功");
});

异步方式二:上面用来递归,下面使用 for 循环 + async await 实现

const fs2 = require("fs").promises;
async function mkdirP2(paths) {
    let arr = paths.split("/");
    for (let i = 0; i < arr.length; i++) {
        let currentPath = arr.slice(0, i + 1).join("/");
        console.log("mkdirP2---currentPath---->", currentPath);
        // 如果文件夹不存在就创建
        try {
            await fs2.access(currentPath);
        } catch (error) {
            console.log(error);
            await fs2.mkdir(currentPath);
        }
    }
}
mkdirP2("c/d/e/f");

目录
相关文章
|
4月前
|
监控 Linux 开发工具
Linux常用指令【文件目录操作】2
Linux常用指令【文件目录操作】
|
4月前
|
Linux Shell
Linux常用指令【文件目录操作】1
Linux常用指令【文件目录操作】
|
11月前
16Linux - 文件管理(删除目录:rmdir)
16Linux - 文件管理(删除目录:rmdir)
25 0
|
Linux Shell
linux常用命令(1)——目录操作命令
linux常用命令(1)——目录操作命令
|
Shell Linux
Linux目录与文件的相关操作
0、关机重启命令 关机命令 sudo shutdown -h now 重启命令 sudo reboot 1、目录的切换 打开终端窗口(”ctrl+alt+t“) 一般使用(”pwd“)显示当前所在的目录 比如:当前目录是在home下面的,与用户名相同的文件夹,可以使用(”cd“)命令来切换目录; 进入下载目录(”cd home/a/下载“)这种从给目录开头的一长串路经”叫做绝对路径“; 进入图片目录(”cd .. /图片/“)".."代表当前路径的上级路径,相对于当前的目录而言的”叫做相对路径“,(”.“)代表当前路径; 如果,想快速切换,上一个所在目录可以(”cd -“); 如果,想快速切换
80 0
|
监控 Linux Shell
Linux常用指令【文件目录操作】
基本语法 pwd (显示当前工作目录的绝对路径)
|
Linux Windows Perl
Linux目录与文件操作
Linux目录与文件操作
Linux目录与文件操作
|
关系型数据库 Java 程序员
目录操作 | 学习笔记
简介:快速学习目录操作
目录操作 | 学习笔记
|
Linux
(二)目录及文件操作
命令:ls[选项][目录/文件] 功能:对于目录,该命令列出该目录下的所有子目录与文件。 对于文件,将列出文件名及其他
148 0
(二)目录及文件操作
|
Linux
如何使用 rmdir 命令删除目录?
rmdir 是您将在开始时学习但很少使用的基本 Linux 命令之一
311 0
如何使用 rmdir 命令删除目录?