Skip to content

ruggeryiury/node-lib

Repository files navigation

About

node-lib is a package that abstracts many internal NodeJS functions into user-friendly, intuitive class subdivisions. With node-lib, things like file and directory path handling, and binary data writing becomes easier to do!

Core modules

  • FilePath | DirPath: Handle file and directory paths easily with built-in handling methods to read, write, copy, modify, and others.
  • BinaryReader | BinaryWriter | StreamWriter: Parse and write binary files easily with several format parsing and writing methods.
  • HexStr: Processes hex string with ease.
  • MyObject: Create object maps with type assertion, with built-in methods to convert them to JavaScript object or serialized JSON string.

Basic usage

FilePath

FilePath makes file path handling easy as it could be!

You can initialize a FilePath instance with the class constructor

import { FilePath } from 'node-lib'

const path = 'path/to/file.bin'
const file = new FilePath(path)

or using the static method FilePath.of().

import { FilePath } from 'node-lib'

const path = 'path/to/file.bin'
const file = FilePath.of(path)

FilePath accepts both absolute and relative paths. Relative paths will be resolved from the project working directory your initial script will be called upon.

Class properties

Property Description
path The working path of this class instance.
root The root directory of the file where the path evaluates to.
fullname The name of the file with extension (if any).
name The name of the file (without the extension).
ext The extension of the file (if any), returns an empty string if the provided path accidentally evalutes to a directory.

You can also retrieve all these properties at once as an object using FilePath.toJSON() method.

File stats

You can get systems stats of a file as an object using the FilePath.stat() (async) or the FilePath.statSync() (sync) method.

Path manipulation methods

  • changeFileName(fileName: string | null, fileExt?: string) — Changes the file name of this FilePath and returns a new instantiated FilePath with the new file name.
  • changeThisFileName(fileName: string | null, fileExt?: string) — Changes the file name of this FilePath instance.

  • changeFileExt(fileExt: string) — Changes the file extension of this FilePath and returns a new instantiated FilePath with the new file extension.
  • changeThisFileExt(fileExt: string) — Changes the file extension of this FilePath instance.

  • gotoDir(directoryName: string) — Returns a new instantiated DirPath, resolving the path to a new directory relative from this file root path.
  • gotoFile(fileName: string) — Returns a new instantiated FilePath, resolving the path to a new file relative from this file root path.

Checking file existence

You can use the property FilePath.exists to check the file existence. FilePath.exists is a getter that will always check once it's referenced.

import { FilePath } from 'node-lib'

const path: string = 'path/to/file.bin'
const file: FilePath = FilePath.of(path)
console.log(file.exists) // <- true

await file.deleteFile()
console.log(file.exists) // <- false

File reading methods

  • open(flags?: string | number) — Asynchronously opens a FileHandle.

  • read(encoding?: BufferEncodingOrNull) — Reads the entire contents of a file. Returns a Buffer or a string depending on the encoding provided.
  • readSync(encoding?: BufferEncodingOrNull) — Synchronous version of read().

  • readLines(options?: ReadLinesOptions) — Reads a file as a list of lines. Automatically trims and splits the file content on newline characters. Assumes the file content is text (not binary).
  • readLinesSync(options?: ReadLinesOptions) — Synchronous version of readLines().

  • readJSON(encoding?: BufferEncodingText) — Reads a JSON file and parses it into an object. Attempts to decode the content using the provided encoding, then parses it using JSON.parse.
  • readJSONSync(encoding?: BufferEncodingText) — Synchronous version of readJSON().

  • readOffset(byteOffset: number, byteLength?: number) — Reads a portion of a file starting from a specific byte offset. If byteLength is provided, reads that many bytes using a file descriptor. Otherwise, reads the whole file and returns a subarray starting at the offset.

File writing methods

  • write(data: FileAsyncWriteDataTypes, encoding?: BufferEncodingOrNull, replace?: boolean) — Writes data to a file, optionally replacing it if it already exists. Supports writing strings or buffers to a file with optional encoding. Throws an error if the file exists and replace is set to false.
  • writeSync(data: FileSyncWriteDataTypes, encoding?: BufferEncodingOrNull, replace?: boolean) — Synchronous version of write().

  • writeWithBOM(data: StringOrBuffer, encoding?: BufferEncodingBOM, replace?: boolean) — Writes a UTF-8 or UTF-16 encoded text file with a Byte Order Mark (BOM). Automatically prepends a BOM to the content. If encoding is not specified or is a variant of UTF-8, it uses UTF-8 with BOM. If encoding is 'utf16le', it writes the content using UTF-16LE. Throws an error if the file exists and replace is set to false.
  • writeWithBOMSync(data: StringOrBuffer, encoding?: BufferEncodingBOM, replace?: boolean) — Synchronous version of writeWithBOM().

  • createWriteStream(encoding?: BufferEncodingOrNull) — Creates a writable file stream at the specified path. If a file already exists at the path, it will be deleted before creating the stream. Optionally accepts an encoding; if null is passed, defaults to utf8.
  • createWriteStreamSync(encoding?: BufferEncodingOrNull) — Synchronous version of createWriteStream().

  • pipe<T>(source: PipelineSource<T>, options?: PipelineOptions) — Pipes the given source stream or iterable into an internal writable stream and returns a promise that resolves when the piping is complete or rejects on error.

Other methods

  • copy(destPath: FilePathLikeTypes, replace?: boolean) — Copies a file from a source path to a destination path. If the destination path already exists:

    • Throws an error unless replace is set to true.
    • If replace is true, deletes the existing file before copying.

    Automatically resolves relative destination paths based on the source file's directory.

  • copySync(destPath: FilePathLikeTypes, replace?: boolean) — Synchronous version of copy().


  • rename(newPath: FilePathLikeTypes, replace?: boolean) — Renames (or moves) a file from an old path to a new path. If the new path already exists:

    • Throws an error unless replace is true.
    • If replace is true, deletes the destination file before renaming.

    Automatically resolves relative newPath values based on the directory of the oldPath.

  • renameSync(newPath: FilePathLikeTypes, replace?: boolean) — Synchronous version of copy().

  • move(newPath: FilePathLikeTypes, replace?: boolean) — Alias to rename().

  • moveSync(newPath: FilePathLikeTypes, replace?: boolean) — Alias to renameSync().


  • delete() — Deletes a file at the specified path if it exists. Resolves the given path and performs a safe check before deletion to avoid errors.
  • deleteSync() — Synchronous version of delete().
  • remove() — Alias to delete().
  • removeSync() — Alias to deleteSync().

  • generateHash(algorithm: AllHashAlgorithms, digest: BinaryToTextEncoding) — Asynchronously computes a cryptographic hash from the contents of the file.

DirPath

You can initialize a DirPath instance with the class constructor

import { DirPath } from 'node-lib'

const path = 'path/to/directory'
const dir = new DirPath(path)

or using the static method DirPath.of().

import { DirPath } from 'node-lib'

const path = 'path/to/directory'
const dir = DirPath.of(path)

DirPath accepts both absolute and relative paths. Relative paths will be resolved from the project working directory your initial script will be called upon.

Class properties

Property Description
path The working path of this class instance.
root The root directory of the file where the path evaluates to.
name The name of the file (without the extension).

You can also retrieve all these properties at once as an object using DirPath.toJSON() method.

Directory stats

You can get systems stats of a directory as an object using the DirPath.stat() (async) or the DirPath.statSync() (sync) method.

Path manipulation methods

  • changeDirName(dirName: string) — Changes the directory name of this DirPath and returns a new instantiated DirPath with the new directory name.
  • changeThisDirName(dirName: string) — Changes the directory name of this DirPath instance.

  • gotoDir(directoryName: string) — Returns a new instantiated DirPath, resolving the path to a new directory relative from this directory path.
  • gotoFile(fileName: string) — Returns a new instantiated DirPath, resolving the path to a new directory relative from this directory path.

Checking directory existence

You can use the property DirPath.exists to check the directory existence. DirPath.exists is a getter that will always check once it's referenced.

import { DirPath } from 'node-lib'

const path = 'path/to/directory'
const dir = DirPath.of(path)
console.log(dir.exists) // <- true

await dir.deleteDir()
console.log(dir.exists) // <- false