npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node_custom_utils

v0.3.3

Published

Optimize your Node.js code and elevate its personal utility with this intricately designed Node.js package, custom-tailored to streamline your development tasks for both personal and commercial applications.

Downloads

21

Readme

npm downloads per month

Generate Snowflake and Unique IDs

  1. Create an instance of the ID class with a machine ID

    const idGenerator = new ID(1);
    // Generate a Snowflake ID
    const snowflakeID = idGenerator.getSnowflakeID();
    console.log(`Snowflake ID: ${snowflakeID}`);
    // Generate a Unique ID
    const uniqueID = idGenerator.getUniqueID();
    console.log(`Unique ID: ${uniqueID}`);

File upload

  1. Local server.

    // Uploads a file to the local server.
    const uploadedFileUrl = await FileUploadToLocalServer({
      req,
      pathToUpload,
      imageKeyWord,
    });
    // Deletes a file located at the specified path.
    DeleteLocalServerFile(filePathToDelete);
  2. S3 Spaces

    // Allowed file extensions for upload
    const allowedExtensions = [".jpg", ".png", ".jpeg"];
    
    // Upload the file to the specified bucket
    const uploadedFileKey = await FileUploadToSpacesBucket({
      req,
      pathToUpload,
      imageKeyWord,
      fileTypes: allowedExtensions,
    });
    // Attempt to delete the file
    const isDeleted = await DeleteFileSpacesBucket(fileKey);

Removes the specified text from the array.

const array = ['hello', 'world', 'hello'];
const result = array.removeText('hello');
console.log(result); // Output: ['world']

Verify the Integrity of Color Hash Codes

  1. Checks if the given string represents a valid hexadecimal color code.

    "#123".cIsValidColorCode(); // true
    "#12345".cIsValidColorCode(); // false
    "red".cIsValidColorCode(); // false

Handle string-based URL manipulation.

  1. Parses the query parameters from a given URL string and returns them as a Map.

    const urlString = "https://example.com/path?name=John&age=30";
    const queryParams = cGetQueryParams(urlString);
    console.log(queryParams.get("name")); // Output: 'John'
    console.log(queryParams.get("age")); // Output: '30'
  2. Validates a URL string.

    const isValid = cIsValidUrl("https://www.example.com");
    console.log(isValid); // Output: true
  3. The cUpdateQueryParam function is an extension of the global String object in TypeScript. It provides a method for updating or adding query parameters to a URL string. This can be especially useful in web development when you need to modify URLs dynamically.

    // Original URL
    const originalUrl = "https://example.com/page?name=John";
    
    // Updated URL with a new query parameter or modified existing parameter
    const updatedUrl = originalUrl.cUpdateQueryParam("age", "30");
    
    console.log(updatedUrl);
    // Output: 'https://example.com/page?name=John&age=30'

Example Usage of Utility Functions

  1. Define a sample Express route handler

    const sampleRouteHandler = (req: Request, res: Response) => {
      try {
        // Construct a JSON response using the `toJson` function
        toJson(res, {
          data: responseData, // Sample data to be included in the response
          message: "Sample response for README",
        });
      } catch (error) {
        // Handle errors and construct an error response using the `errorResponse` function
        errorResponse(res, error);
      }
    };
  2. Check if a value has data

    const hasValue = hasData("Sample Data"); // true if the value is not empty
  3. Check if a date is valid

    const isDateValid = isValidDate("2023-09-07"); // true if the date is valid
  4. Check if a date and time is valid

    const isDateTimeValid = isValidDateTime("2023-09-07 14:30:00"); // true if the date and time are valid
  5. Add one day to a date

    const newDate = adjustDateByDays(new Date("2023-09-07"));
  6. Get an image URL with a placeholder if no data is available

    const imageUrl = getImg("https://example.com/image.jpg"); // Provided URL if data exists, otherwise a placeholder URL
  7. Compare two JSON objects for deep equality

    const obj1 = { key1: "value1", key2: { nestedKey: "nestedValue" } };
    const obj2 = { key1: "value1", key2: { nestedKey: "nestedValue" } };
    
    const areEqual = compareJSONObjects(obj1, obj2); // true if objects are deeply equal
  8. Convert a number to a string or empty string if it's zero

    const stringValue = convertNumberToStringOrEmpty(0); // "" (empty string)

Converts a JSON string to a JavaScript object.

const jsonData = '{"name": "John", "age": 30}';
const jsonObject = cToJson(jsonData);
console.log(jsonObject); // Output: { name: 'John', age: 30 }
const data = { name: "Alice", age: 25 };
const convertedData = cToJson(data);
console.log(convertedData); // Output: { name: 'Alice', age: 25 }
const invalidData = "not a valid JSON";
try {
  const result = cToJson(invalidData); // Throws an error
} catch (error) {
  console.error(error.message); // Output: "The data cannot be converted into a JSON format."
}

Filters the input list to keep only the unique objects.

cGetUniqueObjects()

// Example Usage
const inputList = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 1, name: "Alice" }, // Duplicate object
];

const uniqueObjects = cGetUniqueObjects(inputList);
console.log(uniqueObjects);

Base64

Encodes a string into Base64 format. cEncodeToBase64()

let originalString = "Hello World!";
let encodedString = originalString.cEncodeToBase64();
console.log(`Encoded String: ${encodedString}`);

Decodes a Base64 encoded string. cDecodeFromBase64()

let originalString = "Hello World!";
let decodedString = encodedString.cDecodeFromBase64();
console.log(`Decoded String: ${decodedString}`);

Converts a value to a boolean in a safe manner.

const result = cToBooleanSafe("true"); // Returns true
const result2 = cToBooleanSafe("false"); // Returns false
const result3 = cToBooleanSafe(1); // Returns true

sha256

cSha256("data");

Asynchronously converts a CSV/Excel file to a JSON array.

csvToJson("/path/to/file.csv").then((data) => console.log(data));
excelToJson("/path/to/excel-file.xlsx").then((data) => console.log(data));

Asynchronously converts an array of JSON objects to a CSV/Excel file.

const data = [
  { name: "John Doe", age: 30, email: "[email protected]" },
  { name: "Jane Doe", age: 25, email: "[email protected]" },
];
jsonToCsv(data, "users").then((path) => console.log(path));
jsonToExcel(data, "users")
  .then((filePath) => {
    console.log("Excel file created at:", filePath);
  })
  .catch((error) => {
    console.error("Error creating Excel file:", error);
  });

Generates an array of objects, each representing a distinct month (and year) within a specified date range.

const details = cGetYearMonthDetailsBetweenDates("2022-01-01", "2022-03-01");

Output: [ { year: 2022, monthNumber: 1, monthName: "January" }, { year: 2022, monthNumber: 2, monthName: "February" }, { year: 2022, monthNumber: 3, monthName: "March" } ]

Gets the months that fall between two given dates.

  1. Get full month names between January 1, 2022, and March 1, 2022

    cGetMonthBetweenDates("2022-01-01", "2022-03-01", true);

    // Returns ["January", "February", "March"]

  2. Get month numbers between January 1, 2022, and March 1, 2022

    cGetMonthBetweenDates("2022-01-01", "2022-03-01");

    // Returns ["1", "2", "3"]

Checks if two dates fall within the same calendar year.

  1. cHaveSameYear("2023-01-01", "2023-12-31");

    // Returns true

  2. cHaveSameYear("2023-12-31", "2024-01-01");

    // Returns false

Changes the month and optionally the day of a given date string.

  1. // Change the month of March 15, 2023, to February
    cChangeDateMonthAndDay("2023-03-15", 2);
    // Returns "2023-02-15"
  2. // Change the month and day of March 15, 2023, to February 28
    cChangeDateMonthAndDay("2023-03-15", 2, 28);
    // Returns "2023-02-28"
  3. // Attempt to set an invalid date (February 30th)
    cChangeDateMonthAndDay("2023-03-15", 2, 30);
    // Logs "Invalid day for the given month" and returns "2023-03-15"

Converts a floating-point number to an integer.

  1. cConvertDoubleToInt(NaN);

    returns 0

  2. cConvertDoubleToInt(1.0);

    returns 100

  3. cConvertDoubleToInt(123.45);

    returns 12345

Fetches IP address details

cGetIpDetails("192.168.1.1")
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error("Error fetching IP details:", error);
  });

Contributers