open-index/open-npm huggingface dataset:
npm package: @loxjs/cache
Description: A Node.js module that provides a simple caching layer on top of Redis
Author: Zen Li
Latest version: 2.0.5

# @loxjs/cache

`@loxjs/cache` is a Node.js module that provides a simple caching layer on top of Redis. It allows for easy setting and retrieval of JSON objects with optional expiration settings.

## Features

- Simple key-value storage
- Automatic JSON serialization and deserialization
- Optional key prefixing
- Configurable expiration for cached items

## Installation

Install the module with npm:

```bash
npm install @loxjs/cache --save
```

Or with yarn:

```bash
yarn add @loxjs/cache
```

## Usage

Here's how to use `@loxjs/cache` in your project.

### Initializing

First, require and initialize the module:

```
const Cache = require('@loxjs/cache');

const cache = new Cache({
  redis: {
    // Redis configuration options
  },
  prefix: 'myPrefix', // optional key prefix
  exType: 'EX',       // default expiration type ('EX' for seconds)
  exDuration: 3600    // default expiration duration (in seconds)
});
```

### Setting a Value

To cache a value with an optional expiration:

```
cache.set('myKey', { my: 'value' }, {
  exType: 'EX',       // 'EX' for seconds, 'PX' for milliseconds
  exDuration: 60      // expiration time in seconds
});
```

If `exType` and `exDuration` are not specified, the defaults provided during initialization will be used.

### Getting a Value

To retrieve a value from the cache:

```
cache.get('myKey').then(value => {
  console.log(value); // outputs: { my: 'value' }
});
```


## Contributing

Contributions to `@loxjs/cache` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/cache`!
npm package: @loxjs/config
Description: A configuration management library for Node.js applications
Author: Zen Li
Latest version: 2.1.7

# @loxjs/config

A configuration management library for Node.js applications, `@loxjs/config` provides a simple and fluent API for getting and setting configuration values, bulk updates, and merging configurations with defaults.

## Features

- Easy configuration value retrieval with dot notation
- Set individual configuration values or in bulk
- Merge configurations with default values
- Fluent API for checking equality or inequality of configuration values

## Installation

Install `@loxjs/config` using npm:

```sh
npm install @loxjs/config
```

Or using yarn:

```sh
yarn add @loxjs/config
```

## Usage

Here's a quick overview of how you can use `@loxjs/config`.

### Importing

First, import and initialize the module:

```
const Config = require('@loxjs/config');

const config = new Config({
  // Initial configuration values
});
```

### Setting Configuration Values

To set a configuration value:

```
config.set('path.to.setting', 'value');
To set multiple configuration values at once:

config.bulkSet({
  'path.to.setting': 'value',
  'another.path.to.setting': 'another value'
});
```

### Getting Configuration Values

To get a configuration value, use:

```
const value = config.get('path.to.setting');
```

To get a configuration value with a `defaultValue`, `defaultValue` is returned when configuration value is `undefined`:

```
const value = config.get('path.to.setting', 'defaultValue');
```

To get a configuration value and set it if it doesn't exist:

```
const value = config.geset('path.to.setting', 'defaultValue');
```

### Checking Configuration Values

To check if a configuration value equals a specific value:

```
const isEqual = config.eq('path.to.setting', 'value');
```

To check if a configuration value does not equal a specific value:

```
const isNotEqual = config.ne('path.to.setting', 'value');
```

### Merging Configuration Values

To merge a set of default values with existing configuration:

```
const mergedConfig = config.merge('path.to.setting', {
  defaultKey: 'defaultValue',
  anotherDefaultKey: 'anotherDefaultValue'
});
```


## Contributing

Contributions to `@loxjs/config` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/config`!
npm package: @loxjs/count-words
Description: Count the number of words in a string
Author: Zen Li
Latest version: 2.0.5

# @loxjs/count-words

`@loxjs/count-words` is a simple utility function for Node.js that counts the number of words in a given string, treating continuous sequences of English letters, numbers, and symbols as a single word, and removing punctuation and whitespace.

## Features

- Counts words by treating continuous sequences of English alphanumeric characters and symbols as single words
- Removes punctuation and excess whitespace, including spaces, tabs, and newlines
- Handles multilingual text by stripping non-English punctuation and symbols

## Installation

Install `@loxjs/count-words` using npm:

```sh
npm install @loxjs/count-words
```

Or using yarn:

```sh
yarn add @loxjs/count-words
```

## Usage

To use `@loxjs/count-words` in your project:

```
const countWords = require('@loxjs/count-words');

const myString = "Hello, world! This is a test string.";
const wordCount = countWords(myString);

console.log(wordCount); // Output will be the number of words in `myString`
```

## Functionality

The countWords function performs the following steps:

1. Validates that the input is a non-empty string.
2. Replaces all whitespace characters (including spaces, tabs, and newlines) with a placeholder symbol.
3. Treats continuous sequences of English alphanumeric characters and symbols as single words by replacing them with a unique character.
4. Strips all punctuation from the string.
5. Counts the remaining characters in the string, which correspond to the number of words.


## Contributing

Contributions to `@loxjs/count-words` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/count-words`!
npm package: @loxjs/express-client-ip
Description: An npm module for obtaining a client's IP address in Express.js applications.
Author: Zen Li
Latest version: 2.1.2

# @loxjs/express-client-ip

`@loxjs/express-client-ip` is an npm module for obtaining a client's IP address in Express.js applications. It accounts for requests forwarded by proxy servers, such as Caddy, Nginx, Apache, CloudFlare, etc., and attempts to extract the original client IP address from various HTTP header fields.

## Features

 - Retrieves IP addresses from HTTP headers like `X-Real-IP`, `X-Forwarded-For`, `CF-Connecting-IP`, and others.
 - Compatible with both IPv4 and IPv6 addresses.
 - Provides middleware function for easy integration into Express.js applications.
 - Automatically handles scenarios involving multiple proxy servers.
 - Returns the client's IP address for a request or `null` if undetermined.

## Installation

Install using npm:

```sh
npm install @loxjs/express-client-ip
```

Or with yarn:

```sh
yarn add @loxjs/express-client-ip
```

## Usage

### As Middleware

In your Express.js application, you can use `@loxjs/express-client-ip` as middleware to set the `req.clientIp` property on every request.

```
const express = require('express');
const getClientIP = require('@loxjs/express-client-ip');

const app = express();

// Apply middleware
app.use(getClientIP.middleware);

app.get('/', (req, res) => {
  res.send(`Your IP is: ${req.clientIp}`);
});

app.listen(3000);
```

### As a Function

You can also directly call the `getIP` function to obtain the client's IP address.

```
const getClientIP = require('@loxjs/express-client-ip');

app.get('/some-path', (req, res) => {
  const ip = getClientIP(req);
  res.send(`Your IP is: ${ip}`);
});
```

## API Reference

### getIP Function

 - `getIP(req)`: Extracts the client IP address from the request object.
   - req: The request object from Express.js.

### getIP.middleware Function

 - `getIP.middleware`: An Express.js middleware that adds the client's IP address to the `req.clientIp` property.


## Contributing

Contributions to `@loxjs/express-client-ip` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/express-client-ip`!
npm package: @loxjs/load-js-modules
Description: Provides a convenient way to dynamically load JavaScript modules from a specified directory.
Author: Zen Li
Latest version: 1.0.3

# @loxjs/load-js-modules

The `@loxjs/load-js-modules` module provides a convenient way to dynamically load JavaScript modules from a specified directory. It supports loading individual files as well as entire directories with an optional auto-load feature.

## Installation

```sh
npm install @loxjs/load-js-modules
```

Or with yarn:

```sh
yarn add @loxjs/load-js-modules
```

## Usage

To use this module, you first need to import it and then call the `loadJSModules` function with the appropriate options.

### Basic Example

```
const loadJSModules = require('@loxjs/load-js-modules');

// Load modules from a specific directory
const modules = loadJSModules({ dir: './path/to/modules', autoLoad: true });

// Use the loaded modules
modules.forEach((mod) => {
  console.log(`Module ${mod.moduleName} loaded`, mod.module);
});
```

### Advanced Usage

You can also load modules without automatically requiring them, which allows you to require them at a later point in your application.

```
const loadJSModules = require('@loxjs/load-js-modules');

// Load module information without auto-loading
const modules = loadJSModules({ dir: './path/to/modules', autoLoad: false });

// Require a specific module when needed
const specificModule = modules.find(mod => mod.moduleName === 'specificModule');
const loadedModule = specificModule.loadModule();

// Use the loaded module
console.log(`Module ${specificModule.moduleName} loaded`, loadedModule);
```

## API

### `loadJSModules(options)`

Loads JavaScript modules from the specified directory.

#### Options

- `dir` (String): The directory to load modules from. This can be a relative or absolute path.
- `autoLoad` (Boolean): If true, modules are automatically required when loaded. Defaults to false.

#### Returns

An array of module objects with the following properties:

- `autoLoad` (Boolean): The autoLoad option passed to loadJSModules.
- `fileExtname` (String): The file extension of the module.
- `fileName` (String): The name of the file.
- `filePath` (String): The full path to the module file.
- `moduleName` (String): The name of the module, derived from the file name.
- `loadModule` (Function): A function that, when called, will require the module.
- `module` (Object|null): The required module if autoLoad is true, otherwise null.


## Contributing

Contributions to `@loxjs/load-js-modules` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/load-js-modules`!
npm package: @loxjs/node-base64
Description: A Node.js module that provides URL-safe Base64 encoding and decoding.
Author: Zen Li
Latest version: 2.0.3

# @loxjs/node-base64

`@loxjs/node-base64` is a Node.js module that provides URL-safe Base64 encoding and decoding. It follows the RFC 4648 Spec for Base64 encoding, where '+' is encoded as '-' and '/' is encoded as '_'. Additionally, it can remove padding characters '=' for a more compact representation.

## Installation

```sh
npm install @loxjs/node-base64
```

Or with yarn:

```sh
yarn add @loxjs/node-base64
```

## Usage

This module exports three main functions: `encode`, `decode`, and `validate`. You can use these functions to handle URL-safe Base64 strings within your Node.js applications.

### Encoding to URL Safe Base64

```
const base64 = require('@loxjs/node-base64');

// Encode a string to Base64
const encodedString = base64.encode('Hello World!');
console.log(encodedString); // Output: SGVsbG8gV29ybGQh (without padding '=' characters)
```

### Encoding with Padding Characters

```
const base64 = require('@loxjs/node-base64');

// Encode a string to Base64 and keep padding '=' characters
const encodedStringWithEq = base64.encode('Hello World!', true);
console.log(encodedStringWithEq); // Output: SGVsbG8gV29ybGQh== (with padding '=' characters)
```

### Decoding from URL Safe Base64

```
const base64 = require('@loxjs/node-base64');

// Decode a URL Safe Base64 string
const decodedString = base64.decode('SGVsbG8gV29ybGQh');
console.log(decodedString); // Output: Hello World!
```

### Validating a URL Safe Base64 String

```
const base64 = require('@loxjs/node-base64');

// Validate a URL Safe Base64 string
const isValid = base64.validate('SGVsbG8gV29ybGQh');
console.log(isValid); // Output: true
```

## API

### `encode(str, [witheq])`

Encodes a buffer or string to URL Safe Base64.

- `str` (String|Buffer): The string or buffer to encode.
- `witheq` (Boolean): Optional. If `true`, retains padding '=' characters. Defaults to `false`.

### `decode(str)`

Decodes a URL Safe Base64 string to its original representation.

- `str` (String): The URL Safe Base64 string to decode.

### `validate(str)`

Validates whether a string is a URL Safe Base64 encoded string.

- `str` (String): The string to validate.


## Contributing

Contributions to `@loxjs/node-base64` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/node-base64`!
npm package: @loxjs/node-local-ip
Description: A simple Node.js module that helps you retrieve the local IPv4 address of your machine.
Author: Zen Li
Latest version: 2.0.3

# @loxjs/node-local-ip

`@loxjs/node-local-ip` is a simple Node.js module that helps you retrieve the local IPv4 address of your machine. It automatically determines the correct network interface based on your operating system (e.g., `eth0` for Linux, `en0` for Mac) and provides the IPv4 address associated with that interface.

## Installation

```sh
npm install @loxjs/node-local-ip
```

Or with yarn:

```sh
yarn add @loxjs/node-local-ip
```

## Usage

To use this module to get your local IPv4 address, simply require and call the module. It will return the local IPv4 address as a string.

### Example

```
const getLocalIp = require('@loxjs/node-local-ip');

const myLocalIp = getLocalIp();
console.log('My local IP address is:', myLocalIp);
```

The above code will output your machine's local IP address to the console.

## How It Works

The module uses Node.js's built-in `os` module to access the network interfaces of the machine. It then looks for the `IPv4` address within the network interfaces object.

## Error Handling

If the module encounters an error while trying to retrieve the network interfaces, it will return the error object.

### Example with Error Handling

```
const getLocalIp = require('@loxjs/node-local-ip');

try {
    const myLocalIp = getLocalIp();
    console.log('My local IP address is:', myLocalIp);
} catch (err) {
    console.error('Error retrieving local IP:', err);
}
```


## Contributing

Contributions to `@loxjs/node-local-ip` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/node-local-ip`!
npm package: @loxjs/password
Description: A module designed for password strength checking and random password generation.
Author: Zen Li
Latest version: 1.1.3

# @loxjs/password

`@loxjs/password` is a Node.js module designed for password strength checking and random password generation. It provides a simple interface to evaluate the complexity of a given password and to generate a strong, random password based on specified criteria.

## Installation

```sh
npm install @loxjs/password
```

Or with yarn:

```sh
yarn add @loxjs/password
```

## Usage

This module exports two main functions: `checkStrength` for checking the password strength and `random` for generating a random password.

### Checking Password Strength

The `checkStrength` function evaluates the complexity of a password by analyzing its composition of numbers, uppercase letters, lowercase letters, and special characters.

```
const { checkStrength } = require('@loxjs/password');

// Check the strength of a password
const password = 'YourP@ssw0rd';
const strength = checkStrength(password, 7); // Minimum length is 7

console.log(strength); // Output will be a number between 0 (weak) to 4 (strong)
```

The function returns a number representing the strength level:

- 0: Weak (less than minimum length)
- 1: Weak (only one type of character)
- 2: Moderate (two types of characters)
- 3: Strong (three types of characters)
- 4: Very Strong (all four types of characters)

### Generating a Random Password

The `random` function generates a random password that includes a mix of numbers, lowercase and uppercase letters, and special characters.

```
const { random } = require('@loxjs/password');

// Generate a simple random password
const passwordLength = 10; // Specify the length of the password
const newPassword = random(passwordLength);

console.log(newPassword); // Output will be a random password
```

## API

### `checkStrength(password, minLength)`

Checks the strength of the given password.

- `password` (String): The password to check.
- `minLength` (Number): The minimum length for the password to be considered not weak.

### `random(length)`

Generates a random password.

- `length` (Number): The desired length of the generated password.


## Contributing

Contributions to `@loxjs/password` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/password`!
npm package: @loxjs/sleep
Description: A simple promise-based sleep function for Node.js, `@loxjs/sleep` provides a straightforward way to introduce a delay in your async functions or promise chains.
Author: Zen Li
Latest version: 2.0.5

# @loxjs/sleep

A simple promise-based sleep function for Node.js, `@loxjs/sleep` provides a straightforward way to introduce a delay in your async functions or promise chains.

## Installation

Install the module with npm:

```bash
npm install @loxjs/sleep
```

Or with yarn:

```bash
yarn add @loxjs/sleep
```

## Usage

To use `@loxjs/sleep`, simply require it in your module and call it with an amount of time in milliseconds.

```
const sleep = require('@loxjs/sleep')

// In an async function
async function example() {
    console.log('Sleeping for 2 seconds...')
    await sleep(2000); // Sleeps for 2000 milliseconds (2 seconds)
    console.log('Woke up after 2 seconds!')
}

// Immediately-Invoked Function Expression (IIFE) with async
(async () => {
    console.log('Sleeping for 3 seconds...')
    await sleep(3000); // Sleeps for 3000 milliseconds (3 seconds)
    console.log('Woke up after 3 seconds!')
})()
```

## API

`@loxjs/sleep` exports a single function:

### sleep(time)
Returns a Promise that resolves after the specified time.

#### Parameters

 - `time` (Number) - The amount of time to sleep in milliseconds.

#### Returns

 - `Promise` - A Promise that resolves after the specified amount of time.

## Example

```
const sleep = require('@loxjs/sleep')

async function fetchData() {
    // Simulate a delay in fetching data
    console.log('Fetching data in 1 second...')
    await sleep(1000)
    console.log('Data fetched!')
}

fetchData()
```


## Contributing

Contributions to `@loxjs/sleep` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/sleep`!
npm package: @loxjs/snowflake
Description: A module that generates unique IDs based on Twitter's Snowflake algorithm.
Author: Zen Li
Latest version: 1.1.3

# @loxjs/snowflake

`@loxjs/snowflake` is a Node.js module that generates unique, distributed, time-sorted identifiers using the Twitter Snowflake algorithm. Snowflake IDs are composed of a timestamp, a data center identifier, a worker identifier, and a sequence number.

## Features

- Generates unique IDs in a distributed environment.
- IDs are time-based and sorted.
- Can extract timestamp, data center ID, and worker ID from generated IDs.
- High-performance ID generation (over 1 million IDs per second).

## Installation

Install the module with npm:

```sh
npm install @loxjs/snowflake
```

Or with yarn:

```sh
yarn add @loxjs/snowflake
```

## Usage

To use `@loxjs/snowflake`, create a new instance of the `Snowflake` class with optional configuration parameters.

```
const Snowflake = require('@loxjs/snowflake');

// Create a Snowflake ID generator with custom settings
const snowflake = new Snowflake({
  epoch: 1546272000000, // Custom epoch start time (default is 2019/1/1)
  dataCenterId: 1, // Data center identifier
  workerId: 1, // Worker identifier
  sequence: 0 // Initial sequence number
});

// Generate a Snowflake ID
const id = snowflake.nextId();
console.log(`Generated Snowflake ID: ${id}`);
```

### Validating Snowflake IDs

The module provides a method to validate if a given value is a valid Snowflake ID.

```
// Check if a given value is a valid Snowflake ID
const isValid = snowflake.isId(id);
console.log(`Is valid Snowflake ID: ${isValid}`);
```

### Example: Handling ID Generation

```
try {
  const id = snowflake.nextId();
  console.log(`Generated Snowflake ID: ${id}`);
} catch (error) {
  console.error('Error generating Snowflake ID:', error);
}
```


## Contributing

Contributions to `@loxjs/snowflake` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/blob/main/CONTRIBUTING.md).

Enjoy using `@loxjs/snowflake`!
npm package: @loxjs/url-join
Description: Join urls and normalize as in path.join.
Author: Zen Li
Latest version: 1.0.2

# @loxjs/url-join

`@loxjs/url-join` is a Node.js utility module that allows for the concatenation of URL segments into a single, normalized URL. It is a fork of the original [url-join](https://github.com/jfromaniello/url-join) module, modified to support `require` in addition to `import` for module inclusion, making it more accessible for a wider range of Node.js projects.

## Installation

To install the module, use npm or yarn as follows:

```sh
npm install @loxjs/url-join
```

or

```sh
yarn add @loxjs/url-join
```

## Usage

To use this module in your project, simply require it and then call the `urlJoin` function with the URL segments you want to join together:

```
const urlJoin = require('@loxjs/url-join');

const myUrl = urlJoin('http://example.com', 'path', 'to', 'resource');
console.log(myUrl);
// Output: http://example.com/path/to/resource
```

## Examples

Joining URL segments with query parameters:

```
const myUrl = urlJoin('http://example.com', 'search', '?query=node');
// Output: http://example.com/search?query=node
```

Handling trailing slashes:

```
const myUrl = urlJoin('http://example.com/', '/about/');
// Output: http://example.com/about/
```

Support for file protocol:

```
const myUrl = urlJoin('file:///', 'usr', 'local', 'bin');
// Output: file:///usr/local/bin
```

## Acknowledgements

We would like to express our gratitude to the author and contributors of the original [url-join](https://github.com/jfromaniello/url-join) module. `@loxjs/url-join` is built upon the solid foundation they provided, and this modification would not have been possible without their groundwork.

## Features

 - Normalizes URL paths by removing redundant slashes.
 - Correctly handles protocols and slashes specific to file URLs.
 - Supports both `require` and `import` statements for module inclusion.
 - Manages trailing slashes and query parameters in a URL.
 - Throws informative errors for non-string URL segments.

## API

### urlJoin(...args)

Joins all given URL segments and normalizes the result.

Arguments:

 - `...args` (String[]): An array of strings representing each segment of the URL.

Returns:

 - String: A string of the normalized URL.


## Contributing

Contributions to `@loxjs/url-join` are welcome! Please ensure that your contributions adhere to the following guidelines:

 - Write clear, readable, and maintainable code.
 - Follow existing coding styles and practices.
 - Write meaningful commit messages.
 - Update the documentation accordingly.

For more detailed information, please read the [contributing guide](https://github.com/loxjs/mono/CONTRIBUTING.md).

Enjoy using `@loxjs/url-join`!