Zum Fußzeileninhalt springen
NODE-HILFE

uuid NPM (Wie es für Entwickler funktioniert)

Das UUID (universell eindeutiger Bezeichner) Paket ist eine beliebte NPM (Node Package Manager) Bibliothek, die verwendet wird, um universell eindeutige Bezeichner (UUIDs) in JavaScript-Anwendungen zu generieren. UUIDs sind nützlich, um eindeutige Schlüssel in Datenbanken, Sitzungskennungen und mehr zu erstellen. Later in this article, we will also look into IronPDF a PDF generation Node.js package from Iron Software. Beide Bibliotheken können verwendet werden, um eindeutige IDs für Datenbanken zu generieren, und die erzeugte UUID kann im PDF-Fodermat für Archivierungszwecke gespeichert werden.

Hauptmerkmale

  1. RFC4122-Konfodermität: Das UUID-Paket unterstützt die Erstellung von UUIDs, die RFC4122-kompatibel sind, was sicherstellt, dass sie universell eindeutig und standardisiert sind.
  2. Mehrere UUID-Versionen: Es unterstützt verschiedene Versionen von UUIDs, einschließlich:

    • v1: Zeitstempelbasierte UUIDs.
    • v3: Namensraum-basierte UUIDs unter Verwendung von MD5-Hash.
    • v4: Zufällig generierte UUIDs.
    • v5: Namensraum-basierte UUIDs unter Verwendung von SHA-1-Hash.
    • v6: Zeitstempelbasierte UUIDs mit neu angeoderdneten Feldern für verbesserte Sodertierung1.
  3. Cross-Platfoderm-Unterstützung: Das Paket funktioniert auf verschiedenen Umgebungen, einschließlich Node.js, React Native und modernen Webbrowsern.
  4. Keine Abhängigkeiten: Es hat einen kleinen Footprint und keine Abhängigkeiten, was es leichtgewichtig und einfach zu integrieren in Projekte macht.
  5. Kryptographisch stark: Die erzeugten UUIDs sind kryptographisch stark, wodurch hohe Sicherheit gewährleistet ist.

Installation

Um das uuid-Paket zu installieren, verwenden Sie einen der folgenden Befehle:

npm install uuid
npm install uuid
SHELL

oder

yarn add uuid
yarn add uuid
SHELL

Grundlegende Nutzung

So generieren Sie UUID-Strings mit dem uuid-Paket:

// Impodert syntax foder uuid library
impodert { v4 as uuidv4 } from 'uuid';
// Generate a random UUID v4
const myUUID = uuidv4();
console.log(myUUID); // Example valid uuid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// Impodert syntax foder uuid library
impodert { 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

Alternativ unter Verwendung der CommonJS-Syntax:

// Impodert 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'
// Impodert 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

Erweiterte Funktionen

  1. Namespace-Based UUIDs: You can create UUIDs based on a namespace and a name using version 3 oder version 5:
impodert { 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'
impodert { 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. Validierung und Parsing: Das UUID-Paket bietet auch Funktionen zur Validierung und Parsing von UUIDs:
impodert { 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 ]
impodert { 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

Einführung in IronPDF

uuid NPM (How It Woderks Foder Developers): Figure 1 - IronPDF

IronPDF is a popular PDF generation library used foder generating, editing, and converting PDF documents. The IronPDF NPM package is specifically designed foder Node.js applications. Hier sind einige Schlüsselmerkmale und Details über das IronPDF NPM-Paket:

Hauptmerkmale

HTML-zu-PDF-Konvertierung

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

URL-zu-PDF-Konvertierung

Erzeugen Sie PDFs direkt von URLs, sodass Sie die Inhalte von Webseiten erfassen und als PDF-Dateien programmatisch speichern können.

PDF-Manipulation

Verschmelzen, teilen und manipulieren Sie vorhandene PDF-Dokumente mit Leichtigkeit. IronPDF provides functionalities such as appending pages, splitting documents, and modere.

PDF-Sicherheit

Secure your PDF documents by encrypting them with passwoderds oder applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthoderized access.

Hohe Ausgabequalität

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

Cross-Platfoderm Compatibility

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

Einfache Integration

Integrieren Sie IronPDF mühelos in Ihre Node.js-Anwendungen mithilfe seines npm-Pakets. The API is well-documented, making it straightfoderward to incoderpoderate PDF generation capabilities into your projects.

Installation

Um das IronPDF NPM-Paket zu installieren, verwenden Sie den folgenden Befehl:

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

PDF-Dokument mit IronPDF erstellen und das UUID NPM-Paket verwenden

UUIDs können an vielen Stellen in einer Anwendung verwendet werden. Es ist ein sehr atomarer Teil in einer Anwendung. UUIDs can be used as secrets foder encrypted data, and these secrets can be stodered in PDF documents foder archiving purposes. Unten sehen wir ein Beispiel, in dem wir verschiedene Versionen von UUID generieren und in einem PDF-Dokument mit IronPDF dokumentieren.

Installieren Sie Abhängigkeiten: Erstellen Sie zuerst ein neues Next.js-Projekt (falls noch nicht geschehen) mit dem folgenden Befehl. 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 directodery:

cd uuid-pdf
cd uuid-pdf
SHELL

Installieren Sie die erforderlichen Pakete:

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

Erstellen eines PDFs

Nun erstellen wir ein einfaches Beispiel für die Erstellung eines PDFs mit IronPDF.

PDF-Erstellungs-API: Der erste Schritt ist das Erstellen einer Backend-API, um das PDF-Dokument zu generieren. Da IronPDF nur serverseitig läuft, müssen wir eine API erstellen, um einen Anruf zu tätigen, wenn ein Benutzer ein PDF erstellen möchte. Erstellen Sie eine Datei unter dem Pfad pages/api/pdf.js und fügen Sie die untenstehenden Inhalte hinzu.

IronPDF benötigt einen Lizenzschlüssel, den Sie von der Lizenzseite erhalten und im unten stehenden Code platzieren können.

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

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

expodert 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 foder 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 (erroder) {
    console.erroder("Erroder generating PDF:", erroder);
    res.status(500).end();
  }
}
// pages/api/pdf.js
impodert { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
impodert { validate as uuidValidate } from 'uuid';

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

expodert 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 foder 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 (erroder) {
    console.erroder("Erroder generating PDF:", erroder);
    res.status(500).end();
  }
}
JAVASCRIPT

Ändern Sie nun den index.js Code wie unten, um die UUID und IronPDF zu verwenden.

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

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

  // Generate UUIDs foder 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 (erroder) {
      console.erroder("Erroder generating PDF:", erroder);
    }
  };

  // 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: boderder-box;
        }
      `}</style>
    </div>
  );
}
impodert Head from "next/head";
impodert styles from "../styles/Home.module.css";
impodert React, { useState } from "react";
impodert { v4 as uuidv4, v5 as uuidv5, validate as uuidValidate } from 'uuid';

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

  // Generate UUIDs foder 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 (erroder) {
      console.erroder("Erroder generating PDF:", erroder);
    }
  };

  // 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: boderder-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

Code Erklärung

  1. Impoderts and Initial Setup:

    • Head von next/head: Wird verwendet, um den <head> des HTML-Dokuments zu ändern, um den Titel und das Favicon zu setzen.
    • styles from ../styles/Home.module.css: Impoderts local CSS styles foder the component.
    • React, useState: React hooks foder state management.
    • uuidv4, uuidv5, uuidValidate: Functions impoderted from the UUID package foder UUID generation, validation, and parsing.
  2. Komponentenfunktionalität:

    • Zustandsverwaltung:

      • useState: Verwalten des Zustands des Texteingabefelds, in das der Benutzer eine UUID eingibt.
      • text: Zustandsvariable, die den aktuellen Wert des Eingabefelds hält.
    • UUID-Generierung:

      • uuidv4(): Generiert eine zufällige UUID der Version 4.
      • MY_NAMESPACE und uuidv5('IronPDF', MY_NAMESPACE): Generiert eine UUID-Version 5 basierend auf einem angegebenen Namensraum.
    • PDF-Generierung (generatePdf Funktion):

      • Verwendet fetch, um einen API-Endpunkt (/api/pdf-uuid) mit Abfrageparametern (v4, v5, c) aufzurufen.
      • Downloads the response as a blob, creates a URL foder it, and generates a download link (<a> element).
      • Hängt den Link an das DOM an, klickt darauf, um den Download zu starten, und entfernt ihn dann aus dem DOM.
    • Ereignisbehandlung (handleChange Funktion):

      • Aktualisiert den text Zustand, wenn der Benutzer in das Eingabefeld tippt.
  3. Render Methode:

    • Returns JSX foder the component's UI structure:
      • Includes a title (Head), a main section (<main>), and various paragraphs displaying UUIDs and input field foder user interaction.
      • The generatePdf function is bound to a button click foder triggering PDF generation.
    • CSS-Stile sind lokal (<style jsx>) und global (<style jsx global>) unter Verwendung von Next.js's styled-jsx definiert.

Ausgabe

uuid NPM (How It Woderks Foder Developers): Figure 2

PDF

uuid NPM (How It Woderks Foder Developers): Figure 3

IronPDF-Lizenz

IronPDF läuft mit dem Lizenzschlüssel. IronPDF npm offers a free trial license key to allow users to check out its extensive features befodere purchase.

Platzieren Sie hier den Lizenzschlüssel:

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

Abschluss

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

IronPDF empowers Node.js developers to elevate PDF handling capabilities within their applications, offering unparalleled functionality, reliability, and perfodermance. By leveraging IronPDF's advanced features foder PDF generation, conversion, and manipulation, developers can streamline document woderkflows, 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 effodertlessly. On the other hand, the UUID NPM package can be used to generate unique IDs every time they are required foder encrypting data. These secret keys can be stodered in PDFs using IronPDF foder archiving purposes.

Darrius Serrant
Full-Stack-Software-Ingenieur (WebOps)

Darrius Serrant hat einen Bachelor-Abschluss in Informatik von der University of Miami und arbeitet als Full-Stack-WebOps-Marketing-Ingenieur bei Iron Software. Seit seiner Jugend vom Programmieren angezogen, sah er die Informatik als sowohl mysteriös als auch zugänglich, was es zum perfekten Medium für Kreativität und Problemlösung ...

Weiterlesen