基本概念
- fs.exists已经弃用,可以使用fs.access判断文件夹是否存在,但是官方的建议是在进行文件操作前不要使用fs.access,官方推荐的方式的是直接进行文件操作,有错误再修改
不建议在调用 fs.open() 、 fs.readFile() 或 fs.writeFile() 之前使用 fs.access() 检查一个文件的可访问性。 如此处理会造成紊乱情况,因为其他进程可能在两个调用之间改变该文件的状态。 作为替代,用户代码应该直接打开/读取/写入文件,当文件无法访问时再处理错误。
基本使用
- fs.writeFile回调函数是否有错误都会被激活
- fs.mkdirSync回调函数没有错误不会被激活
const fs = require("fs");const path = require("path");const moment = require("moment");const driArr = [];const year = moment().format("YYYY");driArr.push(year);const month = moment().format("MM");driArr.push(month);const day = moment().format("DD");driArr.push(day);const txt = "helloworld123";const txtName = "msg1.txt";let pathUrl = "";let index = 0;function mk_dir() { ?if (index > driArr.length - 1) return; ?pathUrl += `${driArr[index]}/`; ?console.log(pathUrl); ?console.log(index); ?try { ???index++; ???fs.mkdirSync(pathUrl); ?} catch (err) { ???if (err.code === "EEXIST") { ?????mk_dir(); ???} ?}}function wr_file() { ?fs.writeFile(`${year}/${month}/${day}/${txtName}`, txt, error => { ???if (!error) return; ???if (error.code === "ENOENT") { ?????for (let i = 0; i < driArr.length; i++) { ???????mk_dir(); ?????} ???} ???wr_file(); ?});}wr_file();
nodejs——避免判断创建多级目录
原文地址:https://www.cnblogs.com/wuqiuxue/p/8905263.html