FileEntity
The FileEntity class provides low-level file read and write operations.
It allows scripts and HTTP servers to open, read, write, seek, and close files efficiently.
FileEntity can also be used as a response body for HttpResponse.raw() to serve static or downloadable files.
Overview
FileEntity enables direct file operations, including:
- Opening files in different modes (read, write, read/write, append, etc.)
- Reading and writing binary data (
Dataobjects) - Seeking to a specific offset in the file
- Closing files to release resources
- Returning file streams as HTTP responses
Instance Properties
path: string
The full path of the file represented by this FileEntity instance.
Example:
Instance Methods
seek(offset: number): boolean
Moves the file pointer to the specified byte offset.
Returns true if successful, or false if seeking fails.
Parameters:
Example:
read(size: number): Data
Reads a specified number of bytes from the current file position and returns them as a Data object.
Parameters:
Returns:
A Data object containing the read bytes.
Example:
write(data: Data): void
Writes the provided Data to the current file position.
Throws an error if the file was not opened in a writable mode.
Parameters:
Example:
close(): void
Closes the file and releases the associated resources.
After closing, you should not call read() or write() again.
Example:
Static Methods
static openForReading(path: string): FileEntity
Opens a file in read-only mode. Throws an error if the file does not exist or cannot be read.
Parameters:
Example:
static openNewForWriting(path: string): FileEntity
Opens a file in write-only mode. If the file already exists, it will be overwritten.
Example:
static openForWritingAndReading(path: string): FileEntity
Opens a file in read/write mode. If the file does not exist, it will be created automatically.
Example:
static openForMode(path: string, mode: string): FileEntity
Opens a file using the specified access mode.
The supported modes follow standard POSIX file semantics, but it is strongly recommended to use binary-safe modes such as "rb" or "r+b" for better cross-platform compatibility, since FileEntity performs all read/write operations in binary mode internally.
Parameters:
💡 Note: Always prefer binary-safe modes (those ending with
b), such as"rb","wb", or"r+b". This ensures consistent behavior across platforms and avoids newline or encoding conversion issues, sinceFileEntityhandles all file I/O as binary streams.
Example:
Using FileEntity in HttpResponse
FileEntity can be used directly as the body of an HTTP response via HttpResponse.raw().
This allows serving files or implementing file download endpoints.
Example:
Clients accessing /download will directly receive the file as a download.
