Fylo is a powerful library designed to make file system operations in Node.js convenient, fast, and secure. Supporting Node.js versions 8.16.0 and above, Fylo is ideal for developers working with both modern and legacy versions of the platform. If you need to ensure reliable file and directory operations on older systems, Fylo will be your indispensable tool.
- About the Library
- Working with Files and Directories
- Reading and Writing Streams
- File and Directory Watchers
- License
- Author
- Reporting Issues
- Support the Author
- Conclusion
The development of Fylo started with a real-world challenge: creating software for IoT controllers running Node.js version 8.16.0. We encountered the problem of many modern libraries being incompatible with this version of the platform. Fylo was created to solve this problem, offering a powerful, convenient, and reliable tool for working with files and streams, even supporting outdated Node.js versions.
Fylo is a library that allows you to effortlessly manage files and directories, as well as work with reading and writing streams, ensuring maximum performance with minimal resource usage. With Fylo, your code becomes cleaner, simpler, and more reliable.
Fylo offers a complete set of functions for working with files and directories. Whether you need to check file existence, read its contents, or create a new directory, Fylo provides simple and intuitive methods.
The exists
method allows you to instantly check whether a file exists at a given path. This is particularly useful for
operations that require a preliminary check of file availability.
Fylo provides two versions of this method:
- Asynchronous version
exists
. - Synchronous version
existsSync
.
Parameters:
-
path
(string): The path to the file that needs to be checked.
Return Value:
-
boolean
: Returnstrue
if the file exists, andfalse
otherwise.
import { exists } from 'fylo';
const exists = await exists('/path/to/file.txt');
console.log(`File exists: ${exists}`);
const { exists } = require('fylo');
exists('/path/to/file.txt').then((exists) => {
console.log(`File exists: ${exists}`);
});
import { existsSync } from 'fylo';
const exists = existsSync('/path/to/file.txt');
console.log(`File exists: ${exists}`);
const { existsSync } = require('fylo');
const exists = existsSync('/path/to/file.txt');
console.log(`File exists: ${exists}`);
The readFile
method provides a quick and safe way to read the contents of a file. You can specify the desired encoding
or retrieve the data as a buffer.
Fylo provides two versions of this method:
- Asynchronous version
readFile
. - Synchronous version
readFileSync
.
Parameters:
-
path
(string): The path to the file whose contents need to be read. -
encoding
(BufferEncoding, optional): The encoding for reading the file. Defaults toutf8
.
Return Value:
-
string
orBuffer
: The file contents as a string (if encoding is specified) or a buffer.
import { readFile } from 'fylo';
const content = await readFile('/path/to/file.txt', 'utf8');
console.log(`File content: ${content}`);
const { readFile } = require('fylo');
readFile('/path/to/file.txt', 'utf8').then((content) => {
console.log(`File content: ${content}`);
});
import { readFileSync } from 'fylo';
const content = readFileSync('/path/to/file.txt', 'utf8');
console.log(`File content: ${content}`);
const { readFileSync } = require('fylo');
const content = readFileSync('/path/to/file.txt', 'utf8');
console.log(`File content: ${content}`);
The writeFile
method allows you to easily write data to a file, choosing the appropriate encoding and access mode.
This method is perfect for both creating new files and updating existing ones.
Fylo provides two versions of this method:
- Asynchronous version
writeFile
. - Synchronous version
writeFileSync
.
Parameters:
-
path
(string): The path to the file where the data needs to be written. -
data
(string | Buffer): The data to be written to the file. -
options
(IFileOptions, optional): Additional write options:-
encoding
(BufferEncoding, optional): The encoding of the data. Defaults toutf8
. -
mode
(number, optional): Sets the file's permissions. Defaults to0o666
. -
flag
(TFileModeFlag, optional): The mode for opening the file. Defaults tow
(write and overwrite).
-
Return Value:
void
import { writeFile } from 'fylo';
await writeFile('/path/to/file.txt', 'Hello, World!', { encoding: 'utf8', mode: 0o666, flag: 'w' });
console.log('Data successfully written.');
const { writeFile } = require('fylo');
writeFile('/path/to/file.txt', 'Hello, World!', { encoding: 'utf8', mode: 0o666, flag: 'w' }).then(() => {
console.log('Data successfully written.');
});
import { writeFileSync } from 'fylo';
writeFileSync('/path/to/file.txt', 'Hello, World!', { encoding: 'utf8', mode: 0o666, flag: 'w' });
console.log('Data successfully written.');
const { writeFileSync } = require('fylo');
writeFileSync('/path/to/file.txt', 'Hello, World!', { encoding: 'utf8', mode: 0o666, flag: 'w' });
console.log('Data successfully written.');
The renameFile
method allows you to safely and easily rename or move a file to a new location.
Fylo provides two versions of this method:
- Asynchronous version
renameFile
. - Synchronous version
renameFileSync
.
Parameters:
-
oldPath
(string): The current path to the file. -
newPath
(string): The new path where the file will be moved or renamed.
Return Value:
void
import { renameFile } from 'fylo';
await renameFile('/path/to/file.txt', '/new/path/to/file.txt');
console.log('File renamed.');
const { renameFile } = require('fylo');
renameFile('/path/to/file.txt', '/new/path/to/file.txt').then(() => {
console.log('File renamed.');
});
import { renameFileSync } from 'fylo';
renameFileSync('/path/to/file.txt', '/new/path/to/file.txt');
console.log('File renamed.');
const { renameFileSync } = require('fylo');
renameFileSync('/path/to/file.txt', '/new/path/to/file.txt');
console.log('File renamed.');
The unlink
method allows you to quickly and safely delete an unnecessary file.
Fylo provides two versions of this method:
- Asynchronous version
unlink
. - Synchronous version
unlinkSync
.
Parameters:
-
path
(string): The path to the file that needs to be deleted.
Return Value:
void
import { unlink } from 'fylo';
await unlink('/path/to/file.txt');
console.log('File deleted.');
const { unlink } = require('fylo');
unlink('/path/to/file.txt').then(() => {
console.log('File deleted.');
});
import { unlinkSync } from 'fylo';
unlinkSync('/path/to/file.txt');
console.log('File deleted.');
const { unlinkSync } = require('fylo');
unlinkSync('/path/to/file.txt');
console.log('File deleted.');
Fylo provides tools for simple and convenient directory management, including creation, deletion, and clearing.
The mkdir
method helps you quickly create a new directory, including all missing directories in the path.
Fylo provides two versions of this method:
- Asynchronous version
mkdir
. - Synchronous version
mkdirSync
.
Parameters:
-
path
(string): The path where the new directory should be created. -
options
(IDirectoryOptions, optional): Options for creating the directory:-
recursive
(boolean, optional): Iftrue
, all missing directories in the path are created. Defaults tofalse
. -
mode
(number, optional): Sets the directory's permissions. Defaults to0o777
.
-
Return Value:
void
import { mkdir } from 'fylo';
await mkdir('/path/to/directory', { recursive: true, mode: 0o755 });
console.log('Directory created.');
const { mkdir } = require('fylo');
mkdir('/path/to/directory', { recursive: true, mode: 0o755 }).then(() => {
console.log('Directory created.');
});
import { mkdirSync } from 'fylo';
mkdirSync('/path/to/directory', { recursive: true, mode: 0o755 });
console.log('Directory created.');
const { mkdirSync } = require('fylo');
mkdirSync('/path/to/directory', { recursive: true, mode: 0o755 });
console.log('Directory created.');
The rmdir
method allows you to delete a directory along with all its contents.
Fylo provides two versions of this method:
- Asynchronous version
rmdir
. - Synchronous version
rmdirSync
.
Parameters:
-
path
(string): The path to the directory that needs to be deleted.
Return Value:
void
import { rmdir } from 'fylo';
await rmdir('/path/to/directory');
console.log('Directory deleted.');
const { rmdir } = require('fylo');
rmdir('/path/to/directory').then(() => {
console.log('Directory deleted.');
});
import { rmdirSync } from 'fylo';
rmdirSync('/path/to/directory');
console.log('Directory deleted.');
const { rmdirSync } = require('fylo');
rmdirSync('/path/to/directory');
console.log('Directory deleted.');
The readdir
method returns a list of all files and subdirectories in a specified directory, making content management
easier.
Fylo provides two versions of this method:
- Asynchronous version
readdir
. - Synchronous version
readdirSync
.
Parameters:
-
path
(string): The path to the directory whose contents need to be read.
Return Value:
-
string[]
: An array of strings, each representing a file or subdirectory name.
import { readdir } from 'fylo';
const files = await readdir('/path/to/directory');
console.log('Directory contents:', files);
const { readdir } = require('fylo');
readdir('/path/to/directory').then((files) => {
console.log('Directory contents:', files);
});
import { readdirSync } from 'fylo';
const files = readdirSync('/path/to/directory');
console.log('Directory contents:', files);
const { readdirSync } = require('fylo');
const files = readdirSync('/path/to/directory');
console.log('Directory contents:', files);
The cleardir
method deletes all contents of a directory, leaving the directory itself intact.
Fylo provides two versions of this method:
- Asynchronous version
cleardir
. - Synchronous version
cleardirSync
.
Parameters:
-
path
(string): The path to the directory that needs to be cleared.
Return Value:
void
import { cleardir } from 'fylo';
await cleardir('/path/to/directory');
console.log('Directory cleared.');
const { cleardir } = require('fylo');
cleardir('/path/to/directory').then(() => {
console.log('Directory cleared.');
});
import { cleardirSync } from 'fylo';
cleardirSync('/path/to/directory');
console.log('Directory cleared.');
const { cleardirSync } = require('fylo');
cleardirSync('/path/to/directory');
console.log('Directory cleared.');
Fylo offers efficient tools for working with streams for reading and writing data to files, which is especially important when working with large files.
The ReadStream
class provides a streaming interface for reading data from a file, allowing you to process large files
in parts without loading them entirely into memory.
Constructor Parameters:
-
filePath
(string): The path to the file that needs to be read. -
debug
(boolean, optional): Enables debug mode. Iftrue
, additional logging is activated.
Methods:
-
open(options?: { encoding?: BufferEncoding; highWaterMark?: number }, timeout?: number): Promise<void>
- Opens the stream for reading the file. This method must be called before starting to read.
-
Parameters:
-
options
(optional): Options for opening the stream:-
encoding
(BufferEncoding): The encoding for reading the file. -
highWaterMark
(number): The maximum buffer size for reading.
-
-
timeout
(number): The timeout in milliseconds. If the stream does not open within this time, an error is returned.
-
-
Return Value:
Promise<void>
-
read(): Promise<Buffer | string | null>
- Reads data from the stream if it is not in flowing mode.
-
Return Value:
Promise<Buffer | string | null>
-
pipe(destination: NodeJS.WritableStream | WriteStream, options?: { end?: boolean }): NodeJS.WritableStream | WriteStream
- Pipes data from the read stream to the specified write stream.
-
Parameters:
-
destination
: The write stream to which the data will be piped. -
options
(optional): Options for controlling the piping process:-
end
(boolean): Whether to end the write stream when the read stream finishes. Defaults totrue
.
-
-
-
Return Value: The write stream passed as
destination
.
-
enableFlowingMode(): void
- Enables flowing mode, where data is automatically read and emitted in
data
events.
- Enables flowing mode, where data is automatically read and emitted in
-
disableFlowingMode(): void
- Disables flowing mode.
-
close(timeout?: number): Promise<void>
- Closes the stream.
-
Parameters:
-
timeout
(number): The timeout in milliseconds. If the stream does not close within this time, an error is returned.
-
-
Return Value:
Promise<void>
Usage Example
import { ReadStream } from 'fylo';
const stream = new ReadStream('/path/to/file.txt', true);
stream.on('data', (chunk) => {
console.log('Received data chunk:', chunk);
});
stream
.open()
.then(() => {
console.log('Stream opened.');
})
.catch((err) => {
console.error('Error opening stream:', err);
});
// Using asynchronous iterator
for await (const chunk of stream) {
console.log('Reading data chunk:', chunk);
}
stream.close().then(() => {
console.log('Stream closed.');
});
const { ReadStream } = require('fylo');
const stream = new ReadStream('/path/to/file.txt', true);
stream.on('data', (chunk) => {
console.log('Received data chunk:', chunk);
});
stream
.open()
.then(() => {
console.log('Stream opened.');
})
.catch((err) => {
console.error('Error opening stream:', err);
});
// Using asynchronous iterator
(async () => {
for await (const chunk of stream) {
console.log('Reading data chunk:', chunk);
}
})();
stream.close().then(() => {
console.log('Stream closed.');
});
The WriteStream
class provides an interface for streaming data to a file. This method is especially useful for writing
large amounts of data.
Constructor Parameters:
-
filePath
(string): The path to the file where the data needs to be written. -
debug
(boolean, optional): Enables debug mode. Iftrue
, additional logging is activated.
Methods:
-
open(options?: { encoding?: BufferEncoding; highWaterMark?: number }, timeout?: number): Promise<void>
- Opens the stream for writing data. This method must be called before starting to write.
-
Parameters:
-
options
(optional): Options for opening the stream:-
encoding
(BufferEncoding): The encoding for writing data. -
highWaterMark
(number): The maximum buffer size for writing.
-
-
timeout
(number): The timeout in milliseconds. If the stream does not open within this time, an error is returned.
-
-
Return Value:
Promise<void>
-
write(chunk: Buffer | string): Promise<void>
- Writes a chunk of data to the stream.
-
Parameters:
-
chunk
(Buffer | string): The data to be written to the stream.
-
-
Return Value:
Promise<void>
-
close(timeout?: number): Promise<void>
- Closes the stream.
-
Parameters:
-
timeout
(number): The timeout in milliseconds. If the stream does not close within this time, an error is returned.
-
-
Return Value:
Promise<void>
-
destroy(timeout?: number): Promise<void>
- Destroys the stream, making it unusable for further operations.
-
Parameters:
-
timeout
(number): The timeout in milliseconds. If the stream is not destroyed within this time, an error is returned.
-
-
Return Value:
Promise<void>
Usage Example
import { WriteStream } from 'fylo';
const stream = new WriteStream('/path/to/file.txt', true);
stream
.open()
.then(() => stream.write('Hello, World!'))
.then(() => stream.write('More data'))
.then(() => stream.close())
.then(() => console.log('Data successfully written and stream closed.'))
.catch((err) => console.error('Error working with stream:', err));
const { WriteStream } = require('fylo');
const stream = new WriteStream('/path/to/file.txt', true);
stream
.open()
.then(() => stream.write('Hello, World!'))
.then(() => stream.write('More data'))
.then(() => stream.close())
.then(() => console.log('Data successfully written and stream closed.'))
.catch((err) => console.error('Error working with stream:', err));
Fylo provides convenient tools for monitoring changes in files and directories, allowing you to automate file processing tasks.
The FileWatcher
class allows you to monitor changes in a single file. Both event-based monitoring and polling-based
monitoring are supported.
Constructor Parameters:
-
filePath
(string): The path to the file that needs to be monitored. -
options
(IWatcherOptions, optional): Options for configuring the watcher:-
usePolling
(boolean, optional): Iftrue
, polling is used to monitor changes; otherwise, event-based monitoring is used. -
pollingInterval
(number, optional): The polling interval in milliseconds if polling mode is used. Defaults to500
ms.
-
Methods:
-
start(): void
- Starts the process of monitoring the file. Depending on the settings, either polling or event-based monitoring may be used.
-
stop(): void
- Stops monitoring the file.
-
on(event: 'changed' | 'error', listener: (arg: string | Error) => void): this
- Adds a handler for the specified events.
-
Parameters:
-
event
: The type of event. Possible values:'changed'
(file changed),'error'
(error). -
listener
: The event handler function.
-
Usage Example
import { FileWatcher } from 'fylo';
const watcher = new FileWatcher('/path/to/file.txt', { usePolling: true, pollingInterval: 1000 });
watcher.on('changed', (path) => {
console.log(`File changed: ${path}`);
});
watcher.on('error', (error) => {
console.error(`Error monitoring file: ${error.message}`);
});
watcher.start();
const { FileWatcher } = require('fylo');
const watcher = new FileWatcher('/path/to/file.txt', { usePolling: true, pollingInterval: 1000 });
watcher.on('changed', (path) => {
console.log(`File changed: ${path}`);
});
watcher.on('error', (error) => {
console.error(`Error monitoring file: ${error.message}`);
});
watcher.start();
The DirectoryWatcher
class allows you to monitor changes in a directory. Both polling and event-based monitoring are
supported for tracking additions, deletions, and modifications of files in the directory.
Constructor Parameters:
-
directoryPath
(string): The path to the directory that needs to be monitored. -
options
(IWatcherOptions, optional): Options for configuring the watcher:-
usePolling
(boolean, optional): Iftrue
, polling is used to monitor changes; otherwise, event-based monitoring is used. -
pollingInterval
(number, optional): The polling interval in milliseconds if polling mode is used. Defaults to500
ms.
-
Methods:
-
start(): void
- Starts the process of monitoring the directory. Depending on the settings, either polling or event-based monitoring may be used.
-
stop(): void
- Stops monitoring the directory.
-
on(event: 'added' | 'removed' | 'changed' | 'error', listener: (arg: string | Error) => void): this
- Adds a handler for the specified events.
-
Parameters:
-
event
: The type of event. Possible values:'added'
(file added),'removed'
(file removed),'changed'
(file changed),'error'
(error). -
listener
: The event handler function.
-
Usage Example
import { DirectoryWatcher } from 'fylo';
const watcher = new DirectoryWatcher('/path/to/directory', { usePolling: true, pollingInterval: 1000 });
watcher.on('added', (path) => {
console.log(`File added: ${path}`);
});
watcher.on('removed', (path) => {
console.log(`File removed: ${path}`);
});
watcher.on('changed', (path) => {
console.log(`File changed: ${path}`);
});
watcher.on('error', (error) => {
console.error(`Error monitoring directory: ${error.message}`);
});
watcher.start();
const { DirectoryWatcher } = require('fylo');
const watcher = new DirectoryWatcher('/path/to/directory', { usePolling: true, pollingInterval: 1000 });
watcher.on('added', (path) => {
console.log(`File added: ${path}`);
});
watcher.on('removed', (path) => {
console.log(`File removed: ${path}`);
});
watcher.on('changed', (path) => {
console.log(`File changed: ${path}`);
});
watcher.on('error', (error) => {
console.error(`Error monitoring directory: ${error.message}`);
});
watcher.start();
This project is licensed under the MIT License - see the LICENSE file for details.
The author of the library is David Pobedinskiy.
If you encounter unexpected errors, please let me know by email at qpyracuk@gmail.com or on Telegram.
If my work has helped you simplify your life, you can support me through:
Search npm for other libraries with the @qpyracuk prefix. You might find something useful for your project.
This is an alpha version of the library; if you encounter any bugs, please submit them to the GitHub Issues.
The library's functionality will not change—only the internal components will be updated in case of bugs or shortcomings. The names and results of the functions and methods will remain unchanged.