@contextjs/io
Version:
File system utilities for reading, writing, and inspecting files, directories, and paths.
72 lines (71 loc) • 2.48 kB
JavaScript
import { Throw } from "@contextjs/system";
import { copyFileSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import * as path from "node:path";
import { FileExistsException } from "../exceptions/file-exists.exception.js";
import { FileNotFoundException } from "../exceptions/file-not-found.exception.js";
import { Directory } from "./directory.js";
import { Path } from "./path.js";
export class File {
static read(file) {
if (Path.isFile(file))
return readFileSync(file, 'utf8');
throw new FileNotFoundException(file);
}
static save(file, content, overwrite = false) {
Throw.ifNullOrWhiteSpace(file);
if (!overwrite && Path.isFile(file))
throw new FileExistsException(file);
const dirname = path.dirname(file);
if (!Directory.exists(dirname))
Directory.create(dirname);
writeFileSync(file, content, 'utf8');
return true;
}
static rename(oldFile, newFile) {
Throw.ifNullOrWhiteSpace(oldFile);
Throw.ifNullOrWhiteSpace(newFile);
if (!this.exists(oldFile))
throw new FileNotFoundException(oldFile);
if (this.exists(newFile))
throw new FileExistsException(newFile);
renameSync(oldFile, newFile);
return true;
}
static delete(file) {
Throw.ifNullOrWhiteSpace(file);
if (this.exists(file)) {
rmSync(file);
return true;
}
return false;
}
static copy(source, target) {
Throw.ifNullOrWhiteSpace(source);
Throw.ifNullOrWhiteSpace(target);
if (!this.exists(source))
throw new FileNotFoundException(source);
if (this.exists(target))
throw new FileExistsException(target);
const dirname = path.dirname(target);
if (!Directory.exists(dirname))
Directory.create(dirname);
copyFileSync(source, target);
return true;
}
static exists(file) {
return Path.isFile(file);
}
static getName(file) {
Throw.ifNullOrWhiteSpace(file);
return path.basename(file);
}
static getDirectory(file) {
Throw.ifNullOrWhiteSpace(file);
return path.dirname(file);
}
static getExtension(file) {
Throw.ifNullOrWhiteSpace(file);
const normalizedPath = Path.normalize(file);
return path.extname(normalizedPath).slice(1).toLowerCase();
}
}