>  기사  >  웹 프론트엔드  >  Node.js에서 폴더 작성에 대해 알아보기

Node.js에서 폴더 작성에 대해 알아보기

青灯夜游
青灯夜游앞으로
2020-12-07 17:51:363351검색

이 글에서는 Node.js에서 폴더 작성을 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

Node.js에서 폴더 작성에 대해 알아보기

관련 권장 사항: "node js tutorial"

fs.Dir & fs.Dirent

fs.Dir은 반복 가능한 디렉터리 스트림 클래스이고, fs.Dirent는 fs.Dir 항목을 통과하여 얻은 디렉터리입니다. , 파일 또는 디렉토리의 하위 디렉토리일 수 있습니다.

fs.Dir

  • dir.path: 디렉토리의 읽기 전용 경로
  • dir.read(): callabck가 전달되지 않으면 함수가 반환됩니다. Promise 및 반복자를 읽습니다. 다음 디렉터리 항목은 Promise를 반환합니다. 해결 후 fs.Dirent 또는 null을 얻습니다(읽을 디렉터리 항목이 더 이상 없는 경우)
  • dir.close(): callabck 함수가 전달되지 않은 경우 , Promise가 반환되고 디렉터리의 하위 레이어가 닫힙니다. 리소스 핸들

fs.Dirent

  • dirent.name
  • dirent.isDirectory()
  • dirent.isFile()
  • dirent.isSymbolicLink()

fs.opendir

fs.opendir (path[, options], callback) 디렉토리를 열고 fs.Dir 객체를 반환합니다fs.opendir(path[, options], callback) 打开一个目录,返回 fs.Dir 对象

const fs = require('fs/promises');

async function print(path) {
  const dir = await fs.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
}
print('./').catch(console.error);

可以通过 dir.read() 迭代 dir

const fs = require('fs/promises');

async function print(path) {
  const dir = await fs.opendir(path);
  let dirent = await dir.read();
  while (dirent) {
    console.log(dirent.name);
    dirent = await dir.read();
  }

  dir.close();
}
print('./').catch(console.error);

fs.readdir

fs.readdir(path[, options], callback) 读取目录的内容,回调有两个参数 (err, files),其中 files 是目录中的文件名的数组(不包括 '.' 和 '..')
options

  • encoding:默认值 utf8,如果 encoding 设置为 'buffer',则返回的文件名是 Buffer 对象
  • withFileTypes:默认值 false,设置为 true 后回调函数 files 数组将包含 fs.Dirent 对象
const fs = require('fs/promises');

async function print(path) {
  const files = await fs.readdir(path);
  for (const file of files) {
    console.log(file);
  }
}
print('./').catch(console.error);

fs.mkdir

fs.mkdir(path[, options], callback) 创建目录
options

  • recursive:默认值 false,设置为 true 时候相当命令 mkdir -p 会把不存在的目录创建
  • mode:默认值 0o777,Windows 不支持
// 创建 /tmp/a/apple 目录,无论是否存在 /tmp 和 /tmp/a 目录。
fs.mkdir('/tmp/a/apple', { recursive: true }, err => {
  if (err) throw err;
});

fs.rmdir

fs.rmdir(path[, options], callback)

const fs = require('fs');

fs.rmdir('./tmp', { recursive: true }, err => console.log);

dirrrreee

fs.readdir
  • fs.readdir(path[, options], callback)은 디렉토리의 내용을 읽습니다(err, files). ), 여기서 files는 디렉터리의 파일 이름입니다. ('.' 및 '..' 제외)
  • options
  • encoding: 인코딩이 'buffer'로 설정된 경우 기본값은 utf8입니다. ', 반환된 파일 이름은 Buffer 객체입니다.
withFileTypes: 기본값 false, set true가 되면 콜백 함수 파일 배열에 fs.Dirent 객체

rrreee

fs.mkdir가 포함됩니다.

fs.mkdir(path[, options], callback) 디렉토리 만들기

options

recursive: 기본값은 false입니다. true로 설정하면 mkdir -p 명령이 실행됩니다. code>는 존재하지 않는 디렉토리를 생성합니다🎜🎜mode: 기본값은 0o777, Windows에서는 지원하지 않습니다🎜🎜rrreee

fs.rmdir🎜🎜fs.rmdir(path[ , 옵션], 콜백) fs.rmdir은 폴더🎜options🎜🎜🎜recursive를 삭제하는 데 사용됩니다. 기본값은 false입니다. true인 경우 반복적인 디렉터리 삭제를 수행합니다. 재귀 모드에서는 경로가 존재하지 않는 경우 오류가 보고되지 않으며 실패 시 작업이 재시도됩니다. 🎜🎜retryDelay: 기본값 100, 예외 후 재시도 사이에 대기하는 시간(밀리초)입니다. recursive 옵션이 true가 아닌 경우 이 옵션은 무시됩니다. 🎜🎜maxRetries: 기본값은 0이며, EBUSY, EMFILE, ENFILE, ENOTEMPTY 또는 EPERM 오류가 발생한 경우 Node.js입니다. will 작업은 각 시도마다 retryDelay 밀리초의 선형 백오프로 재시도됩니다. recursive가 false인 경우 이 옵션은 무시됩니다🎜🎜rrreee🎜🎜이전에는 rmdir은 빈 폴더만 삭제할 수 있었지만 이제는 파일과 함께 삭제할 수 있습니다🎜🎜🎜더 많은 프로그래밍 관련 지식을 보려면 🎜프로그래밍 튜토리얼🎜을 방문하세요! ! 🎜

위 내용은 Node.js에서 폴더 작성에 대해 알아보기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제