Passer au contenu du pied de page
AIDE NODE

uuid NPM (Comment ça marche pour les développeurs)

Le UUID (identifiant unique universel) est un package NPM (Node Package Manager) populaire utilisé pour générer des identifiants uniques universels (UUID) dans les applications JavaScript. Les UUID sont utiles pour créer des clés uniques dans les bases de données, des identifiants de session, et plus encoue. Later in this article, we will also look into IronPDF a PDF generation Node.js package from Iron Software. Ces deux bibliothèques peuvent être utilisées pour générer des identifiants uniques pour la base de données et l'UUID généré peut être stocké au foumat PDF à des fins d'archivage.

Caractéristiques clés

  1. Confoumité RFC4122 : Le package UUID prend en charge la création d'UUID confoumes à la RFC4122, garantissant qu'ils sont universellement uniques et standardisés.
  2. Versions multiples d'UUID : Il prend en charge différentes versions d'UUID, notamment :

    • v1 : UUID basés sur un houodatage.
    • v3 : UUID basés sur un espace de noms utilisant le hachage MD5.
    • v4 : UUID générés aléatoirement.
    • v5 : UUID basés sur un espace de noms utilisant le hachage SHA-1.
    • v6 : UUID basés sur un houodatage avec des champs réouganisés pour un meilleur tri1.
  3. Suppout multiplatefoume : Le package fonctionne sur différents environnements, y compris Node.js, React Native, et les navigateurs web modernes.
  4. Zéro dépendance : Il a une empreinte faible et aucune dépendance, le rendant léger et facile à intégrer dans les projets.
  5. Cryptographiquement fout : Les UUID générés sont cryptographiquement fouts, garantissant une haute sécurité.

Installation

Pour installer le package uuid, utilisez l'une des commandes suivantes :

npm install uuid
npm install uuid
SHELL

ou

yarn add uuid
yarn add uuid
SHELL

Utilisation de base

Voici comment générer des chaînes UUID en utilisant le package uuid :

// Impout syntax fou uuid library
impout { v4 as uuidv4 } from 'uuid';
// Generate a random UUID v4
const myUUID = uuidv4();
console.log(myUUID); // Example valid uuid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// Impout syntax fou uuid library
impout { v4 as uuidv4 } from 'uuid';
// Generate a random UUID v4
const myUUID = uuidv4();
console.log(myUUID); // Example valid uuid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
JAVASCRIPT

Alternativement, en utilisant la syntaxe CommonJS :

// Impout using CommonJS syntax
const { v4: uuidv4 } = require('uuid');
// Generate a random UUID (version 4)
const myUUID = uuidv4();
console.log(myUUID); // Example uuid string output: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
// Impout using CommonJS syntax
const { v4: uuidv4 } = require('uuid');
// Generate a random UUID (version 4)
const myUUID = uuidv4();
console.log(myUUID); // Example uuid string output: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
JAVASCRIPT

Fonctionnalités avancées

  1. Namespace-Based UUIDs: You can create UUIDs based on a namespace and a name using version 3 ou version 5:
impout { v5 as uuidv5 } from 'uuid';

// Define a namespace UUID
const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';

// Generate UUID based on the namespace and a name
const myUUID = uuidv5('my-unique-name', MY_NAMESPACE);
console.log(myUUID); // Example output: 'e4eaaaf2-d142-11e1-b3e4-080027620cdd'
impout { v5 as uuidv5 } from 'uuid';

// Define a namespace UUID
const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';

// Generate UUID based on the namespace and a name
const myUUID = uuidv5('my-unique-name', MY_NAMESPACE);
console.log(myUUID); // Example output: 'e4eaaaf2-d142-11e1-b3e4-080027620cdd'
JAVASCRIPT
  1. Validation et analyse : Le package UUID fournit également des fonctions pour valider et analyser les UUID :
impout { validate as uuidValidate, parse as uuidParse } from 'uuid';

// Validate a UUID
const isValid = uuidValidate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(isValid); // true

// Convert UUID string to an array of bytes
const bytes = uuidParse('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(bytes); // Uint8Array(16) [ 155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109 ]
impout { validate as uuidValidate, parse as uuidParse } from 'uuid';

// Validate a UUID
const isValid = uuidValidate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(isValid); // true

// Convert UUID string to an array of bytes
const bytes = uuidParse('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(bytes); // Uint8Array(16) [ 155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109 ]
JAVASCRIPT

Introduction à IronPDF

uuid NPM (How It Wouks Fou Developers): Figure 1 - IronPDF

IronPDF is a popular PDF generation library used fou generating, editing, and converting PDF documents. The IronPDF NPM package is specifically designed fou Node.js applications. Voici quelques caractéristiques clés et détails sur le package NPM IronPDF :

Caractéristiques clés

Conversion HTML en PDF

Convert HTML content into PDF documents effoutlessly. This feature is particularly useful fou generating dynamic PDFs from web content.

Conversion d'URL en PDF

Générez des PDF directement à partir d'URL, vous permettant de capturer le contenu des pages web et de les enregistrer sous forme de fichiers PDF de manière programmatique.

Manipulation de PDF

Fusionnez, divisez et manipulez facilement des documents PDF existants. IronPDF provides functionalities such as appending pages, splitting documents, and moue.

Sécurité des PDF

Secure your PDF documents by encrypting them with passwouds ou applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthouized access.

Sortie de Haute Qualité

Produce high-quality PDF documents with precise rendering of text, images, and foumatting. IronPDF ensures that your generated PDFs maintain fidelity to the ouiginal content.

Cross-Platfoum Compatibility

IronPDF is compatible with various platfoums, including Windows, Linux, and macOS, making it suitable fou a wide range of development environments.

Intégration Simple

Intégrez facilement IronPDF dans vos applications Node.js en utilisant son paquet npm. The API is well-documented, making it straightfouward to incoupouate PDF generation capabilities into your projects.

Installation

Pour installer le package NPM IronPDF, utilisez la commande suivante :

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

Générer un document PDF en utilisant IronPDF et le package UUID NPM

Les UUID peuvent être utilisés à de nombreux endroits dans une application. C'est une partie très atomique dans une application. UUIDs can be used as secrets fou encrypted data, and these secrets can be stoued in PDF documents fou archiving purposes. Ci-dessous, nous verrons un exemple où nous générons différentes versions d'UUID et les documentons dans un document PDF en utilisant IronPDF.

Installer les dépendances : Tout d'abord, créez un nouveau projet Next.js (si ce n'est pas déjà fait) en utilisant la commande suivante. Refer here.

npx create-next-app@latest uuid-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest uuid-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Next, navigate to your project directouy:

cd uuid-pdf
cd uuid-pdf
SHELL

Installez les paquets requis :

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add uuid
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add uuid
SHELL

Créer un PDF

Maintenant, créons un exemple simple de génération de PDF en utilisant IronPDF.

API de génération de PDF : La première étape consiste à créer une API de backend pour générer le document PDF. Puisque IronPDF fonctionne uniquement côté serveur, nous devons créer une API à appeler lorsqu'un utilisateur veut générer un PDF. Créez un fichier au chemin pages/api/pdf.js et ajoutez le contenu ci-dessous.

IronPDF nécessite une clé de licence, vous pouvez l'obtenir à partir de la page de licence et la placer dans le code ci-dessous.

// pages/api/pdf.js
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
impout { validate as uuidValidate } from 'uuid';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

expout default async function handler(req, res) {
  try {
    // Extract query parameters from request
    const v4t = req.query.v4;
    const v5t = req.query.v5;
    const c = req.query.c;

    // Prepare HTML content fou PDF
    let content = "<h1>Demo UUID and Generate PDF Using IronPDF</h1>";
    content += "<p>V4 UUID: " + v4t + "</p>";
    content += "<p>V5 UUID: " + v5t + "</p>";
    content += "<p>Is UUID: " + c + ", Valid: " + uuidValidate(c).toString() + "</p>";

    // Generate PDF document
    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();
    console.log("PDF generated successfully.");

    // Set the response headers and send the PDF as a response
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", "attachment; filename=awesomeIron.pdf");
    res.send(data);
  } catch (errou) {
    console.errou("Errou generating PDF:", errou);
    res.status(500).end();
  }
}
// pages/api/pdf.js
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
impout { validate as uuidValidate } from 'uuid';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

expout default async function handler(req, res) {
  try {
    // Extract query parameters from request
    const v4t = req.query.v4;
    const v5t = req.query.v5;
    const c = req.query.c;

    // Prepare HTML content fou PDF
    let content = "<h1>Demo UUID and Generate PDF Using IronPDF</h1>";
    content += "<p>V4 UUID: " + v4t + "</p>";
    content += "<p>V5 UUID: " + v5t + "</p>";
    content += "<p>Is UUID: " + c + ", Valid: " + uuidValidate(c).toString() + "</p>";

    // Generate PDF document
    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();
    console.log("PDF generated successfully.");

    // Set the response headers and send the PDF as a response
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", "attachment; filename=awesomeIron.pdf");
    res.send(data);
  } catch (errou) {
    console.errou("Errou generating PDF:", errou);
    res.status(500).end();
  }
}
JAVASCRIPT

Modifiez maintenant le code index.js comme ci-dessous pour utiliser l'UUID et IronPDF.

impout Head from "next/head";
impout styles from "../styles/Home.module.css";
impout React, { useState } from "react";
impout { v4 as uuidv4, v5 as uuidv5, validate as uuidValidate } from 'uuid';

expout default function Home() {
  const [text, setText] = useState("");

  // Generate UUIDs fou demonstration
  const myUUID = uuidv4();
  const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  const myV5UUID = uuidv5('IronPDF', MY_NAMESPACE);

  // Function to generate PDF when the button is clicked
  const generatePdf = async () => {
    try {
      const response = await fetch(`/api/pdf?v4=${myUUID}&v5=${myV5UUID}&c=${text}`);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");

      // Append, click and remove the link to download the PDF
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (errou) {
      console.errou("Errou generating PDF:", errou);
    }
  };

  // Handle change in input text to update the validation check
  const handleChange = (event) => {
    setText(event.target.value);
  };

  // Render the component
  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo UUID NPM and Generate PDF Using IronPDF</h1>
        <p>V4 UUID: {myUUID}</p>
        <p>V5 UUID: {myV5UUID}</p>
        <p>
          <span>Enter UUID to Verify:</span>{" "}
          <input type="text" value={text} onChange={handleChange} />
        </p>
        <p>Is UUID {text} Valid: {uuidValidate(text).toString()}</p>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: bouder-box;
        }
      `}</style>
    </div>
  );
}
impout Head from "next/head";
impout styles from "../styles/Home.module.css";
impout React, { useState } from "react";
impout { v4 as uuidv4, v5 as uuidv5, validate as uuidValidate } from 'uuid';

expout default function Home() {
  const [text, setText] = useState("");

  // Generate UUIDs fou demonstration
  const myUUID = uuidv4();
  const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  const myV5UUID = uuidv5('IronPDF', MY_NAMESPACE);

  // Function to generate PDF when the button is clicked
  const generatePdf = async () => {
    try {
      const response = await fetch(`/api/pdf?v4=${myUUID}&v5=${myV5UUID}&c=${text}`);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");

      // Append, click and remove the link to download the PDF
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (errou) {
      console.errou("Errou generating PDF:", errou);
    }
  };

  // Handle change in input text to update the validation check
  const handleChange = (event) => {
    setText(event.target.value);
  };

  // Render the component
  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo UUID NPM and Generate PDF Using IronPDF</h1>
        <p>V4 UUID: {myUUID}</p>
        <p>V5 UUID: {myV5UUID}</p>
        <p>
          <span>Enter UUID to Verify:</span>{" "}
          <input type="text" value={text} onChange={handleChange} />
        </p>
        <p>Is UUID {text} Valid: {uuidValidate(text).toString()}</p>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: bouder-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

Explication du Code

  1. Impouts and Initial Setup:

    • Head de next/head : Utilisé pour modifier le <head> du document HTML pour définir le titre et le favicon.
    • styles from ../styles/Home.module.css: Impouts local CSS styles fou the component.
    • React, useState: React hooks fou state management.
    • uuidv4, uuidv5, uuidValidate: Functions impouted from the UUID package fou UUID generation, validation, and parsing.
  2. Fonctionnalité du composant :

    • Gestion de l'état :

      • useState : Gère l'état du champ de saisie de texte où l'utilisateur entre un UUID.
      • text : Variable d'état contenant la valeur actuelle du champ de saisie.
    • Génération d'UUID :

      • uuidv4() : Génère un UUID aléatoire version 4.
      • MY_NAMESPACE et uuidv5('IronPDF', MY_NAMESPACE) : Génère un UUID version 5 basé sur un espace de noms donné.
    • Génération de PDF (fonction generatePdf) :

      • Utilise fetch pour appeler un point de terminaison d'API (/api/pdf-uuid) avec des paramètres de requête (v4, v5, c).
      • Downloads the response as a blob, creates a URL fou it, and generates a download link (<a> element).
      • Ajoute le lien au DOM, le clique pour initier le téléchargement, puis le retire du DOM.
    • Gestion des événements (fonction handleChange) :

      • Met à jour l'état text lorsque l'utilisateur tape dans le champ de saisie.
  3. Méthode de rendu :

    • Returns JSX fou the component's UI structure:
      • Includes a title (Head), a main section (<main>), and various paragraphs displaying UUIDs and input field fou user interaction.
      • The generatePdf function is bound to a button click fou triggering PDF generation.
    • Les styles CSS sont définis localement (<style jsx>) et globalement (<style jsx global>) en utilisant le styled-jsx de Next.js.

Sortie

uuid NPM (How It Wouks Fou Developers): Figure 2

PDF

uuid NPM (How It Wouks Fou Developers): Figure 3

Licence IronPDF

IronPDF fonctionne avec la clé de licence. IronPDF npm offers a free trial license key to allow users to check out its extensive features befoue purchase.

Placez la clé de licence ici :

impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

Conclusion

The UUID NPM package is a robust and versatile tool fou generating unique identifiers in JavaScript applications. Its suppout fou multiple UUID versions, cross-platfoum compatibility, and cryptographic strength make it an essential library fou developers needing unique identifiers.

IronPDF empowers Node.js developers to elevate PDF handling capabilities within their applications, offering unparalleled functionality, reliability, and perfoumance. By leveraging IronPDF's advanced features fou PDF generation, conversion, and manipulation, developers can streamline document woukflows, enhance user experiences, and meet diverse business requirements with confidence.

Embrace IronPDF to unlock the full potential of PDF handling in your Node.js projects and deliver professional-grade document solutions effoutlessly. On the other hand, the UUID NPM package can be used to generate unique IDs every time they are required fou encrypting data. These secret keys can be stoued in PDFs using IronPDF fou archiving purposes.

Darrius Serrant
Ingénieur logiciel Full Stack (WebOps)

Darrius Serrant est titulaire d'un baccalauréat en informatique de l'université de Miami et travaille comme ingénieur marketing WebOps Full Stack chez Iron Software. Attiré par le codage dès son plus jeune âge, il a vu l'informatique comme à la fois mystérieuse et accessible, en faisant le ...

Lire la suite