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 data writing and reading becomes easier to do!
FilePath|DirPath: Handle file and directory paths easily with built-in handling methods to read, write, copy, modify, and others.BinaryReader|BinaryWriter|StreamWriter: Read and write binary files easily with several format parsing and writing methods.HexStr: Processes and converts hex strings with ease.MyObject: Create object maps with type assertion, with built-in methods to convert them to JavaScript object or serialized JSON string.
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.
| 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.
You can get systems stats of a file as an object using the FilePath.stat() (async) or the FilePath.statSync() (sync) method.
changeFileName(fileName: string | null, fileExt?: string)— Changes the file name of thisFilePathand returns a new instantiatedFilePathwith the new file name.changeThisFileName(fileName: string | null, fileExt?: string)— Changes the file name of thisFilePathinstance.
changeFileExt(fileExt: string)— Changes the file extension of thisFilePathand returns a new instantiatedFilePathwith the new file extension.changeThisFileExt(fileExt: string)— Changes the file extension of thisFilePathinstance.
gotoDir(directoryName: string)— Returns a new instantiatedDirPath, resolving the path to a new directory relative from this file root path.gotoFile(fileName: string)— Returns a new instantiatedFilePath, resolving the path to a new file relative from this file root path.
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) // <- falseopen(flags?: string | number)— Asynchronously opens aFileHandle.
read(encoding?: BufferEncodingOrNull)— Reads the entire contents of a file. Returns aBufferor a string depending on the encoding provided.readSync(encoding?: BufferEncodingOrNull)— Synchronous version ofread().
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 ofreadLines().
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 usingJSON.parse.readJSONSync(encoding?: BufferEncodingText)— Synchronous version ofreadJSON().
readOffset(byteOffset: number, byteLength?: number)— Reads a portion of a file starting from a specific byte offset. IfbyteLengthis provided, reads that many bytes using a file descriptor. Otherwise, reads the whole file and returns a subarray starting at the offset.
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 andreplaceis set tofalse.writeSync(data: FileSyncWriteDataTypes, encoding?: BufferEncodingOrNull, replace?: boolean)— Synchronous version ofwrite().
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 andreplaceis set tofalse.writeWithBOMSync(data: StringOrBuffer, encoding?: BufferEncodingBOM, replace?: boolean)— Synchronous version ofwriteWithBOM().
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; ifnullis passed, defaults toutf8.createWriteStreamSync(encoding?: BufferEncodingOrNull)— Synchronous version ofcreateWriteStream().
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.
-
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
replaceis set totrue. - If
replaceistrue, deletes the existing file before copying.
Automatically resolves relative destination paths based on the source file's directory.
- Throws an error unless
-
copySync(destPath: FilePathLikeTypes, replace?: boolean)— Synchronous version ofcopy().
-
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
replaceistrue. - If
replaceistrue, deletes the destination file before renaming.
Automatically resolves relative
newPathvalues based on the directory of theoldPath. - Throws an error unless
-
renameSync(newPath: FilePathLikeTypes, replace?: boolean)— Synchronous version ofcopy(). -
move(newPath: FilePathLikeTypes, replace?: boolean)— Alias torename(). -
moveSync(newPath: FilePathLikeTypes, replace?: boolean)— Alias torenameSync().
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 ofdelete().remove()— Alias todelete().removeSync()— Alias todeleteSync().
generateHash(algorithm: AllHashAlgorithms, digest: BinaryToTextEncoding)— Asynchronously computes a cryptographic hash from the contents of the file.
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.
| 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.
You can get systems stats of a directory as an object using the DirPath.stat() (async) or the DirPath.statSync() (sync) method.
changeDirName(dirName: string)— Changes the directory name of thisDirPathand returns a new instantiatedDirPathwith the new directory name.changeThisDirName(dirName: string)— Changes the directory name of thisDirPathinstance.
gotoDir(directoryName: string)— Returns a new instantiatedDirPath, resolving the path to a new directory relative from this directory path.gotoFile(fileName: string)— Returns a new instantiatedDirPath, resolving the path to a new directory relative from this directory path.
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) // <- falsereadDir(recursive?: boolean, returnValueAsStrings?: boolean)— Reads the contents of a directory and returns an array of file/directory paths.readDirSync(recursive?: boolean, returnValueAsStrings?: boolean)— Synchronous version ofreadDir().
writeFileOnDir(fileName: string, data?: FileAsyncWriteDataTypes | null, encoding?: BufferEncodingOrNull, replace?: boolean)— Writes a file inside a specified directory. Automatically resolves the full file path by combining the directory path and the file name. If the file already exists andreplaceis false, an error is thrown.writeFileOnDirSync(fileName: string, data?: FileSyncWriteDataTypes | null, encoding?: BufferEncodingOrNull, replace?: boolean)— Synchronous version ofwriteFileOnDir().
mkDir(recursive?: boolean)— Creates a directory at the specified path. By default, does not create parent directories unlessrecursiveis set totrue.mkDirSync(recursive?: boolean)— Synchronous version ofmkDir().
deleteDir(recursive?: boolean)— Deletes a directory at the specified path. By default, deletes the directory recursively (including its contents).deleteDir(recursive?: boolean)— Synchronous version ofdeleteDir().
searchDir(pattern?: RegExp | string | (RegExp | string)[], recursive?: boolean)— Searches for files and directories in a folder that match a given pattern.searchDirSync(pattern?: RegExp | string | (RegExp | string)[], recursive?: boolean)— Synchronous version ofsearchDir().
MyObject acts as a wrapper to a Map, with explicit conversion method to object and enforced typing.
The BinaryWriter and StreamWriter classes join functions to write text with several encoding types and/or binary data into memory or directly to an output file, respectively.
To initialize a BinaryWriter instance, simply call its constructor! Each subsequent function calls from it will store the provided text/binary data individually, that can be reconstructed as a Buffer object sequentially using the BinaryWriter.toBuffer().
import { BinaryWriter } from 'node-lib'
// Initialize a BinaryWriter instance calling its constructor.
const writer = new BinaryWriter()
// Now you can start writing data into memory!
writer.write(Buffer.from('Hello World!', 'utf-8'))
// Call .toBuffer() to concat all written data into one final buffer object.
const newBuffer = writer.toBuffer() // <- <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 21>The StreamWriter initialization is a little different, you have to use the asynchronous static method StreamWriter.toFile() to automatically stream the written data to file. This class is useful when dealing with big files, since the BinaryWriter store all data into memory.
import { StreamWriter } from 'node-lib'
// Initialize the StreamWriter class pointing the streamed data to a file path.
const writer = await StreamWriter.toFile('path/to/the/new/file.bin')
// Now you can start writing data into the file directly!
writer.write(Buffer.from('Hello World!', 'utf-8'))
// Don't forget to close the stream writing, otherwise manipulating the
// new file might give permission errors when trying to access it. The class
// is automatically closed before going to the garbage collector, but it's
// asynchronous, and you might not be able to manipulate the new file
// instantaneously unless you explicitively await for the closing operation.
await writer.close()
// Now, you can read and manipulte the new file! To speed up the process,
// you can use the "filePath" property to automatically get a FilePath
// instance that points to the new file.
const newFileBuffer = await writer.filePath.read() // <- <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 21>write(value: Buffer | string, encoding: BinaryWriteEncodings)— Writes rawBufferor string values.writeASCII(value: string, allocSize?: number)— Writes any kind of text on the binary file encoded as ASCII.writeLatin1(value: string, allocSize?: number)— Writes any kind of text on the binary file encoded as Latin1.writeUTF8(value: string, allocSize?: number)— Writes any kind of text on the binary file encoded as UTF-8.writeHex(value: HexStringLikeValues, allocSize?: number)— Writes any kind of HEX string text on the binary file as bytes.writePadding(paddingSize: number, fill: number = 0)— Writes a padding-likeBufferfilled with specific value.
writeUInt8(value: number)— Writes an unsigned 8-bit value on the binary file.writeUInt16LE(value: number)— Writes an unsigned 16-bit value on the binary file (little endian mode).writeUInt16BE(value: number)— Writes an unsigned 16-bit value on the binary file (big endian mode).writeUInt24LE(value: number)— Writes an unsigned 24-bit value on the binary file (little endian mode).writeUInt24BE(value: number)— Writes an unsigned 24-bit value on the binary file (big endian mode).writeUInt32LE(value: number)— Writes an unsigned 32-bit value on the binary file (little endian mode).writeUInt32BE(value: number)— Writes an unsigned 32-bit value on the binary file (big endian mode).
writeInt8(value: number)— Writes a signed 8-bit value on the binary file.writeInt16LE(value: number)— Writes a signed 16-bit value on the binary file (little endian mode).writeInt16BE(value: number)— Writes a signed 16-bit value on the binary file (big endian mode).writeInt24LE(value: number)— Writes a signed 24-bit value on the binary file (little endian mode).writeInt24BE(value: number)— Writes a signed 24-bit value on the binary file (big endian mode).writeInt32LE(value: number)— Writes a signed 32-bit value on the binary file (little endian mode).writeInt32BE(value: number)— Writes a signed 32-bit value on the binary file (big endian mode).
writeFloatLE(value: number)— Writes a float number value (32-bit) in little-endian byte order.writeFloatBE(value: number)— Writes a float number value (32-bit) in big-endian byte order.writeDoubleLE(value: number)— Writes a double float number value (64-bit) in little-endian byte order.writeDoubleBE(value: number)— Writes a double float number value (64-bit) in big-endian byte order.
writeUInt64LE(value: number | bigint)— Writes an unsigned 64-bit value on the binary file (little endian mode).writeUInt64BE(value: number | bigint)— Writes an unsigned 64-bit value on the binary file (big endian mode).writeInt64LE(value: number | bigint)— Writes a signed 64-bit value on the binary file (little endian mode).writeInt64BE(value: number | bigint)— Writes a signed 64-bit value on the binary file (big endian mode).
writeUInt8FromBitsArray(bitsArray: BitsArray)— Writes an 8-bit unsigned integer from an array of 8 bit values (0 or 1).writeUInt8FromBitsBooleanArray(booleanArray: BitsBooleanArray)— Writes an 8-bit unsigned integer from an array of 8 boolean values.writeUInt8FromBitString(bitString: string)— Writes an 8-bit unsigned integer from a bit string (A string of exactly 8 characters, each either'0'or'1'.).
writeString(value: string, encoding: BinaryWriteEncodings = 'utf8')— Alias towritewith pre-defined utf-8 encoding value.writeBoolean(value: boolean)— Writes boolean values as an 8-bit unsigned integer, from 0 (meaning false) to 1 (meaning true).