搜索

PythonReactSEOPDF
GitHub Skill

node-fs-best-practices

Node.js filesystem best practices. Use when reviewing or writing code that uses node:fs, especially to avoid wasteful sync reads, incorrect existsSync+statSync checks, or manual recursive deletes.

besidka☆ 26 仓库 Stars1 仓库 Forks

安装与使用

请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。

查看来源 ↗使用指南

技能说明

Node.js fs best practices

Goals

  • Avoid loading entire files into memory when only a slice is needed
  • Avoid redundant and racy filesystem existence checks
  • Prefer correct, efficient recursive delete APIs

Preferred patterns

Read a file slice without loading everything

Avoid readFileSync(path).slice(0, max).

Use streaming or partial reads instead:

import { createReadStream } from 'node:fs'

function readHead(path: string, maxBytes: number) {
  return new Promise<Buffer>((resolve, reject) => {
    const chunks: Buffer[] = []
    const stream = createReadStream(path, { start: 0, end: maxBytes - 1 })

    stream.on('data', (chunk) => {
      chunks.push(chunk)
    })
    stream.on('end', () => {
      resolve(Buffer.concat(chunks))
    })
    stream.on('error', reject)
  })
}

If you already have a file descriptor, use fs.read with an explicit buffer and length.

Check existence by handling stat errors

Avoid existsSync(path) followed by statSync(path).

Prefer a single stat call and handle errors:

import { stat } from 'node:fs/promises'

async function getStat(path: string) {
  try {
    return await stat(path)
  } catch (exception) {
    if (
      exception instanceof Error
      && 'code' in exception
      && (exception as { code?: string }).code === 'ENOENT'
    ) {
      return null
    }

    throw exception
  }
}

This avoids TOCTOU races and covers permission errors correctly.

Delete directories recursively

Avoid manual readdirSync(...).map(...unlinkSync...) loops.

Use the built-in recursive delete:

import { rm } from 'node:fs/promises'

await rm(path, { recursive: true, force: true })

Review checklist

  • No readFileSync(...).slice(...) for partial reads
  • No existsSync before stat or lstat
  • No manual recursive delete loops when rm(..., { recursive: true }) fits
  • Prefer async (node:fs/promises) APIs in server code to avoid blocking

使用示例

查看来源仓库中的使用示例与配置说明。

查看来源 ↗

来源历史

收录时间
2026-03-11
索引更新时间
2026-03-11
Branch
main

收录与同步日期属于本站记录。源码修改历史请查看来源仓库。

GitHub ↗

chat Comments (0)

chat_bubble_outline

No comments yet. Be the first to share your thoughts!