Elide expone node:fs, node:fs/promises, fs.promises y el
alias elide:fs. Los ejemplos siguientes cubren operaciones síncronas, con Promise, con FileHandle
y con flujos.
Uso básico
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 });
}Este ejemplo verifica mkdtempSync, writeFileSync, readFileSync, statSync
y rmSync. Los fallos del sistema de archivos pueden llevar los campos code, errno, syscall, path
y dest.
Promesas y manejadores de archivo
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 });
}Este ejemplo verifica mkdtemp, writeFile, open y rm basados en Promise,
además de FileHandle.read() y FileHandle.close(). Los fallos representativos con Promise
exponen los mismos campos al estilo de Node descritos antes.
writeFile (y FileHandle.writeFile) también aceptan un iterable síncrono o asíncrono
de cadenas y buffers, incluido un flujo Readable:
import { writeFile } from "node:fs/promises";
import { Readable } from "node:stream";
await writeFile("out.txt", Readable.from(["a", "b", "c"]));Flujos
createReadStream y createWriteStream devuelven flujos Readable y Writable.
El siguiente ejemplo verificado copia un archivo temporal:
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 });
}Observación
watch, watchFile, unwatchFile y la superficie de observación con Promise están presentes.
Un observador abierto mantiene vivo el script hasta que se cierra:
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 no está disponible.
Sandbox
El acceso al sistema de archivos no está restringido hasta que se indican opciones de sandbox:
--sandbox--allow-read[=PATHS]--allow-write[=PATHS]--fs-audit
Con un sandbox activo, las operaciones denegadas fallan en lugar de acceder a la ruta.
Consulte elide help sandbox para conocer la precedencia de las opciones y la sintaxis de las listas de rutas.
Consulte la documentación de fs de Node.js para ver las formas estándar de los argumentos.
Reference
Status: Partial · 246 of 264 suite tests pass (93.2%) · since 1.1.0
Exports
| Export | Kind | Status | Notes |
|---|---|---|---|
readFile(), readFileSync() | function | Full | Reads the entire contents of a file |
writeFile(), writeFileSync() | function | Full | Writes data to a file, replacing it if it already exists |
appendFile(), appendFileSync() | function | Full | Appends data to a file, creating it if it does not exist |
stat(), statSync() | function | Full | Retrieves file status information |
mkdir(), mkdirSync() | function | Full | Creates a directory |
rmdir(), rmdirSync() | function | Full | Removes a directory |
unlink(), unlinkSync() | function | Full | Deletes a file |
rename(), renameSync() | function | Full | Renames (moves) a file or directory |
readdir(), readdirSync() | function | Full | Reads the contents of a directory |
access(), accessSync() | function | Full | Tests whether a path is accessible under the given mode |
copyFile(), copyFileSync() | function | Full | Copies a file from src to dest |
chmod(), chmodSync() | function | Full | Changes the permissions of a file |
lstat(), lstatSync() | function | Full | Retrieves file status information without following symbolic links |
realpath(), realpathSync() | function | Full | Resolves all symbolic links and returns the real absolute path |
mkdtemp(), mkdtempSync() | function | Full | Creates a unique temporary directory using a prefix template |
open(), openSync() | function | Full | Opens a file |
close(), closeSync() | function | Full | Closes a file descriptor |
read(), readSync() | function | Full | Reads from a file descriptor into a buffer |
write(), writeSync() | function | Full | Writes to a file descriptor |
fsync(), fsyncSync() | function | Full | Flushes data and metadata of a descriptor |
fdatasync(), fdatasyncSync() | function | Full | Flushes data of a descriptor |
ftruncate(), ftruncateSync() | function | Full | Truncates a file by descriptor |
truncate(), truncateSync() | function | Full | Truncates a file by path |
readlink(), readlinkSync() | function | Full | Reads a symbolic link’s target |
link(), linkSync() | function | Full | Creates a hard link |
symlink(), symlinkSync() | function | Full | Creates a symbolic link |
rm(), rmSync() | function | Full | Removes files and directories |
cp(), cpSync() | function | Full | Copies a directory structure |
statfs(), statfsSync() | function | Full | Returns filesystem statistics |
opendir(), opendirSync() | function | Full | Opens a directory |
glob(), globSync() | function | Full | Returns paths matching a glob |
chown(), chownSync() | function | Full | Changes ownership of a file |
lchown(), lchownSync() | function | Full | Changes ownership of a symlink |
fchown(), fchownSync() | function | Full | Changes ownership by descriptor |
lchmod(), lchmodSync() | function | Not implemented | Changes permissions of a symlink (macOS) |
fchmod(), fchmodSync() | function | Full | Changes permissions by descriptor |
utimes(), utimesSync() | function | Full | Sets file times |
lutimes(), lutimesSync() | function | Full | Sets symlink times |
futimes(), futimesSync() | function | Full | Sets times by descriptor |
fstat(), fstatSync() | function | Full | Retrieves status by descriptor |
exists(), existsSync() | function | Full | Deprecated: asynchronously tests whether a path exists |
createReadStream() | function | Full | Creates a readable stream for a file |
createWriteStream() | function | Full | Creates a writable stream for a file |
watch() | function | Full | Watches for changes on a file or directory |
watchFile() | function | Full | Watches a file for changes by polling its status at an interval |
unwatchFile() | function | Full | Stops watching a file previously watched with watchFile |
promises | property | Full | Promise-based variants of all fs methods (fs/promises) |
constants | property | Full | File system constants such as F_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL |
| top-level constants | constant | Full | F_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL, COPYFILE_FICLONE and 46 more |
fs/promises
| Export | Kind | Status | Notes |
|---|---|---|---|
access() | function | Full | Test a path’s accessibility |
appendFile() | function | Full | Append data to a file |
chmod() | function | Full | Change file permissions |
chown() | function | Full | Change file ownership |
copyFile() | function | Full | Copy a file |
cp() | function | Full | Recursively copy a directory tree |
glob() | function | Full | Match paths against a glob pattern |
lchmod() | function | Full | Change permissions of a symbolic link (macOS) |
lchown() | function | Full | Change ownership of a symbolic link |
link() | function | Full | Create a hard link |
lstat() | function | Full | Retrieve link status (does not follow symlinks) |
lutimes() | function | Full | Set the times of a symbolic link |
mkdir() | function | Full | Create a directory |
mkdtemp() | function | Full | Create a unique temporary directory |
open() | function | Full | Open a file, resolving to a FileHandle |
opendir() | function | Full | Open a directory for iteration |
readdir() | function | Full | Read the contents of a directory |
readFile() | function | Full | Read the entire contents of a file |
readlink() | function | Full | Read the target of a symbolic link |
realpath() | function | Full | Resolve the canonical pathname |
rename() | function | Full | Rename (move) a file or directory |
rm() | function | Full | Remove files and directories |
rmdir() | function | Full | Remove a directory |
stat() | function | Full | Retrieve file status |
statfs() | function | Full | Retrieve filesystem statistics |
symlink() | function | Full | Create a symbolic link |
truncate() | function | Full | Truncate a file |
unlink() | function | Full | Delete a file |
utimes() | function | Full | Set the access and modification times of a file |
watch() | function | Full | Watch a file or directory, returning an async iterator of change events |
writeFile() | function | Full | Write 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.