node笔记_读取目录的文件

67 阅读2分钟

文章目录

⭐前言

大家好,我是yma16,本文分享关于node读取目录文件。
往期文章
node_windows环境变量配置
node_npm发布包
linux_配置node
node_nvm安装配置
node笔记_http服务搭建(渲染html、json)
node笔记_读文件
node笔记_写文件
node笔记_连接mysql实现crud
node笔记_formidable实现前后端联调的文件上传
node笔记_koa框架介绍
node_koa路由
node_生成目录
node_读写excel

⭐fs.readdirSync

读取目录内容

参数

  • path <string> | <Buffer> | <URL>
  • options <string> | <Object>
  • encoding <string> 默认值: 'utf8'
  • withFileTypes <boolean> 默认值: false
    返回: <string[]> | <Buffer[]> | <fs.Dirent[]>

💖 读取目录 不加withFileTypes

读取demo目录的实例,打印
示例目录如图:
read-dir
readdirSync读取 demo目录,打印

const fs=require('fs')
let files = fs.readdirSync('./demo');
console.log(files)

结果如下:
run-node
结论:readdirSync执行之后返回的是字符串数组

💖 读取目录 加withFileTypes

读取demo目录加上withFileTypes参数,打印

const fs=require('fs')
let files = fs.readdirSync('./demo',{withFileTypes:true});
console.log(files)

返回的是对象数组

  • name 名字
  • Symbol(type) 类型 <fs.Dirent>对象
    read-dir

💖 读取目录时 判断元素文件还是目录

fs.statSync(path[, options])

  • path <string> | <Buffer> | <URL>
  • options <Object>
  • bigint <boolean> 返回的 <fs.Stats> 对象中的数值是否应为 bigint。 默认值: false。
  • throwIfNoEntry <boolean> 如果文件系统条目不存在,是否会抛出异常,而不是返回 undefined。 默认值: true。
    返回: <fs.Stats>
    boolean返回判断类型

isFile() 是文件
isDirectory() 是目录

读取demo路径,深度查找目录直到结束,打印文件。

const fs = require('fs')
const path = require('path')

function getDirFiles(getPath) {
	let filesArray = [];

	function findJsonFile(propPath) {
		let files = fs.readdirSync(propPath, {
			withFileTypes: true
		});
		files.forEach(function(item, index) {
			let fPath = path.join(propPath, item.name);
			let stat = fs.statSync(fPath);
			if (stat.isDirectory() === true) {
				// 递归目录
				findJsonFile(fPath);
			}
			if (stat.isFile() === true) {
				filesArray.push(fPath);
				const data=fs.readFileSync(fPath,'utf-8')
				console.log(data)
			}
		});
	}
	findJsonFile(getPath);
	console.log(filesArray);
}

getDirFiles('./demo')

运行结果如下:
run-code

⭐结束

本文分享读取目录文件结束
💖感谢你的阅读 💖
如有错误或者不足欢迎指出!
在这里插入图片描述