node笔记_读取目录的文件
  6DMaaPzJglxt 2023年12月05日 30 0



文章目录

  • ⭐前言
  • ⭐fs.readdirSync
  • 💖 读取目录 不加withFileTypes
  • 💖 读取目录 加withFileTypes
  • 💖 读取目录时 判断元素文件还是目录
  • ⭐结束


⭐前言

大家好,我是yma16,本文分享关于node读取目录文件。

⭐fs.readdirSync

读取目录内容

参数

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

💖 读取目录 不加withFileTypes

读取demo目录的实例,打印

示例目录如图:

node笔记_读取目录的文件_抛出异常


readdirSync读取 demo目录,打印

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

结果如下:

node笔记_读取目录的文件_环境变量配置_02


结论:readdirSync执行之后返回的是字符串数组

💖 读取目录 加withFileTypes

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

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

返回的是对象数组

  • name 名字
  • Symbol(type) 类型 <fs.Dirent>对象
  • node笔记_读取目录的文件_node.js_03


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

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')

运行结果如下:

node笔记_读取目录的文件_环境变量配置_04

⭐结束

本文分享读取目录文件结束

💖感谢你的阅读 💖

如有错误或者不足欢迎指出!

node笔记_读取目录的文件_环境变量配置_05


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月05日 0

暂无评论

推荐阅读
6DMaaPzJglxt