Перейти до вмісту

Довідник API node:fs

API файлової системи, потоки, проміси та керування пісочницею

На цій сторінці

Elide надає node:fs, node:fs/promises, fs.promises і псевдонім elide:fs. Наведені нижче приклади охоплюють синхронні операції, операції на Promise, FileHandle і потоки.

Базове використання

import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "elide-fs-"));
const file = path.join(dir, "hello.txt");

try {
  fs.writeFileSync(file, "hello\n");
  console.log(fs.readFileSync(file, "utf8"));
  console.log(fs.statSync(file).isFile());
} finally {
  fs.rmSync(dir, { recursive: true, force: true });
}

Цей приклад перевіряє mkdtempSync, writeFileSync, readFileSync, statSync і rmSync. Помилки файлової системи можуть містити поля code, errno, syscall, path і dest.

Проміси та дескриптори файлів

import os from "node:os";
import path from "node:path";
import { mkdtemp, open, rm, writeFile } from "node:fs/promises";

const dir = await mkdtemp(path.join(os.tmpdir(), "elide-fs-"));
try {
  const file = path.join(dir, "data.txt");
  await writeFile(file, "hello\n");

  const handle = await open(file, "r");
  try {
    const buffer = Buffer.alloc(64);
    const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
    console.log(buffer.subarray(0, bytesRead).toString());
  } finally {
    await handle.close();
  }
} finally {
  await rm(dir, { recursive: true, force: true });
}

Цей приклад перевіряє mkdtemp, writeFile, open і rm на основі Promise, а також FileHandle.read() і FileHandle.close(). Типові помилки Promise надають ті самі поля в стилі Node, що описані вище.

writeFile (і FileHandle.writeFile) також приймають синхронний або асинхронний ітерований об’єкт із рядків і буферів, зокрема потік Readable:

import { writeFile } from "node:fs/promises";
import { Readable } from "node:stream";

await writeFile("out.txt", Readable.from(["a", "b", "c"]));

Потоки

createReadStream і createWriteStream повертають потоки Readable і Writable. Наведений нижче перевірений приклад копіює тимчасовий файл:

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { pipeline } from "node:stream/promises";

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "elide-fs-"));
try {
  const input = path.join(dir, "input.log");
  const output = path.join(dir, "copy.log");
  fs.writeFileSync(input, "first\nsecond\n");

  await pipeline(fs.createReadStream(input), fs.createWriteStream(output));
  console.log(fs.readFileSync(output, "utf8"));
} finally {
  fs.rmSync(dir, { recursive: true, force: true });
}

Стеження

Наявні watch, watchFile, unwatchFile і інтерфейс стеження на Promise. Відкритий спостерігач підтримує роботу скрипта, доки його не закрито:

import fs from "node:fs";

const watcher = fs.watch(".", (event, name) => {
  console.log(event, name); // rename new.txt
  watcher.close();
});
setTimeout(() => fs.writeFileSync("new.txt", "hello"), 100);

fs.openAsBlob недоступний.

Пісочниця

Доступ до файлової системи не обмежено, доки не передано прапорці пісочниці:

  • --sandbox
  • --allow-read[=PATHS]
  • --allow-write[=PATHS]
  • --fs-audit

Коли пісочниця активна, заборонені операції завершуються помилкою замість доступу до шляху. Пріоритет прапорців і синтаксис списків шляхів описано в elide help sandbox.

Стандартні форми аргументів описано в документації Node.js щодо fs.

Reference

Status: Partial · 246 of 264 suite tests pass (93.2%) · since 1.1.0

Exports

ExportKindStatusNotes
readFile(), readFileSync()functionFullReads the entire contents of a file
writeFile(), writeFileSync()functionFullWrites data to a file, replacing it if it already exists
appendFile(), appendFileSync()functionFullAppends data to a file, creating it if it does not exist
stat(), statSync()functionFullRetrieves file status information
mkdir(), mkdirSync()functionFullCreates a directory
rmdir(), rmdirSync()functionFullRemoves a directory
unlink(), unlinkSync()functionFullDeletes a file
rename(), renameSync()functionFullRenames (moves) a file or directory
readdir(), readdirSync()functionFullReads the contents of a directory
access(), accessSync()functionFullTests whether a path is accessible under the given mode
copyFile(), copyFileSync()functionFullCopies a file from src to dest
chmod(), chmodSync()functionFullChanges the permissions of a file
lstat(), lstatSync()functionFullRetrieves file status information without following symbolic links
realpath(), realpathSync()functionFullResolves all symbolic links and returns the real absolute path
mkdtemp(), mkdtempSync()functionFullCreates a unique temporary directory using a prefix template
open(), openSync()functionFullOpens a file
close(), closeSync()functionFullCloses a file descriptor
read(), readSync()functionFullReads from a file descriptor into a buffer
write(), writeSync()functionFullWrites to a file descriptor
fsync(), fsyncSync()functionFullFlushes data and metadata of a descriptor
fdatasync(), fdatasyncSync()functionFullFlushes data of a descriptor
ftruncate(), ftruncateSync()functionFullTruncates a file by descriptor
truncate(), truncateSync()functionFullTruncates a file by path
readlink(), readlinkSync()functionFullReads a symbolic link’s target
link(), linkSync()functionFullCreates a hard link
symlink(), symlinkSync()functionFullCreates a symbolic link
rm(), rmSync()functionFullRemoves files and directories
cp(), cpSync()functionFullCopies a directory structure
statfs(), statfsSync()functionFullReturns filesystem statistics
opendir(), opendirSync()functionFullOpens a directory
glob(), globSync()functionFullReturns paths matching a glob
chown(), chownSync()functionFullChanges ownership of a file
lchown(), lchownSync()functionFullChanges ownership of a symlink
fchown(), fchownSync()functionFullChanges ownership by descriptor
lchmod(), lchmodSync()functionNot implementedChanges permissions of a symlink (macOS)
fchmod(), fchmodSync()functionFullChanges permissions by descriptor
utimes(), utimesSync()functionFullSets file times
lutimes(), lutimesSync()functionFullSets symlink times
futimes(), futimesSync()functionFullSets times by descriptor
fstat(), fstatSync()functionFullRetrieves status by descriptor
exists(), existsSync()functionFullDeprecated: asynchronously tests whether a path exists
createReadStream()functionFullCreates a readable stream for a file
createWriteStream()functionFullCreates a writable stream for a file
watch()functionFullWatches for changes on a file or directory
watchFile()functionFullWatches a file for changes by polling its status at an interval
unwatchFile()functionFullStops watching a file previously watched with watchFile
promisespropertyFullPromise-based variants of all fs methods (fs/promises)
constantspropertyFullFile system constants such as F_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL
top-level constantsconstantFullF_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL, COPYFILE_FICLONE and 46 more

fs/promises

ExportKindStatusNotes
access()functionFullTest a path’s accessibility
appendFile()functionFullAppend data to a file
chmod()functionFullChange file permissions
chown()functionFullChange file ownership
copyFile()functionFullCopy a file
cp()functionFullRecursively copy a directory tree
glob()functionFullMatch paths against a glob pattern
lchmod()functionFullChange permissions of a symbolic link (macOS)
lchown()functionFullChange ownership of a symbolic link
link()functionFullCreate a hard link
lstat()functionFullRetrieve link status (does not follow symlinks)
lutimes()functionFullSet the times of a symbolic link
mkdir()functionFullCreate a directory
mkdtemp()functionFullCreate a unique temporary directory
open()functionFullOpen a file, resolving to a FileHandle
opendir()functionFullOpen a directory for iteration
readdir()functionFullRead the contents of a directory
readFile()functionFullRead the entire contents of a file
readlink()functionFullRead the target of a symbolic link
realpath()functionFullResolve the canonical pathname
rename()functionFullRename (move) a file or directory
rm()functionFullRemove files and directories
rmdir()functionFullRemove a directory
stat()functionFullRetrieve file status
statfs()functionFullRetrieve filesystem statistics
symlink()functionFullCreate a symbolic link
truncate()functionFullTruncate a file
unlink()functionFullDelete a file
utimes()functionFullSet the access and modification times of a file
watch()functionFullWatch a file or directory, returning an async iterator of change events
writeFile()functionFullWrite data to a file, replacing it if it exists

Not implemented

FileReadStream, FileWriteStream, Utf8Stream, lchmod, lchmodSync, openAsBlob.

Tests: node-api node:fs: 246 pass, 18 fail, 0 error, 30 skipped. Failing: test-fs-promises-file-handle-pull.js, test-fs-promises-file-handle-pullsync.js, test-fs-promises-file-handle-read-worker.js, test-fs-promises-file-handle-writer.js, test-fs-promises-watch.js, test-fs-promises.js, test-fs-read-stream-file-handle.js, test-fs-stat.js, and 10 more.

Чи була ця сторінка корисною?