Skip to footer content
NODE HELP

faye NPM (How It Works For Developers)

IronPDF and Faye play different roles in web development, but their skills work well together. Using WebSocket or other compatible transports, servers, and web clients can communicate in real-time thanks to the NPM package Faye. It offers a straightforward but effective pub/sub messaging system that enables scalable, instantaneous data-sharing web applications. The latest version of Faye is 1.4.0, published 4 years ago. Conversely, another npm package called IronPDF allows developers to programmatically create, modify, and convert PDF documents in Node.js environments.

Developers can improve web applications with real-time PDF production capabilities by integrating Faye with IronPDF. Applications needing the instantaneous generation of PDF reports, dynamic document generation depending on user inputs or real-time data changes, and collaborative document editing scenarios may find this connection very helpful. With the help of IronPDF's PDF creation tools and Faye's real-time simple publish-subscribe messaging features, developers can design data-driven, interactive, and adaptable web apps that meet a variety of user and business objectives.

What is Faye?

A Node.js plugin called Faye makes it easier for clients and servers to communicate in real-time using WebSocket or other compatible transport and WebSocket protocols. It offers a pub/sub messaging mechanism that makes web application communication scalable and effective. By smoothly handling connections and message routing between clients and servers, Faye intends to make deploying real-time features—such as live updates, notifications, and collaborative interactions—less complicated. Faye is frequently integrated by developers to improve their apps with collaborative, interactive, and responsive features that call for real-time data transmission between users and servers.

faye NPM (How It Works For Developers): Figure 1 - Faye

Features of Faye

The Faye NPM module is a useful tool for integrating real-time event messaging into web applications since it provides several important features:

  • WebSocket and Transport Protocol Support: Supporting WebSocket and fallback methods to alternate transport protocols, such as HTTP long-polling, Faye can maintain real-time channels of communication with different browsers and network configurations.

  • Pub/Sub Messaging: With the help of Faye's publish/subscribe messaging pattern, users can subscribe to particular channels (topics) and get updates or messages as soon as they are published there.

  • Scalability: It can effectively manage a large number of concurrent connections and messages thanks to its scalable architecture, making it appropriate for applications that demand great performance and responsiveness.

  • Client-Side and Server-Side Integration: Faye facilitates smooth communication between web clients and servers by integrating both client-side (browser) and server-side (Node.js).

  • Security: To regulate access to channels and messages, it incorporates techniques for protecting WebSocket connections as well as performing authentication and authorization procedures.

  • Ease of Use: Developers may create features like live updates, notifications, chat systems, and more with little configuration by using Faye's straightforward API for setting up and managing real-time communications.

  • Reliability: Faye maintains robust communication channels that are resistant to network outages by managing reconnections and guaranteeing message delivery dependability.

  • Customization and Extensibility: With the use of plugins, extensions, and unique adapters, developers can increase Faye's capability and provide specialized solutions to meet certain application needs.

Create and Config Faye

Both the client-side integration and the server-side Faye instance must be set up to construct and configure Faye using NPM in a Node.js environment. Here's a how-to manual to get you going:

Server-Side Setup

Install Faye

Install the Faye package first:

npm install faye
npm install faye
SHELL

Create Faye Server

Make sure the Faye server is configured by creating a server.js file in Node.js:

// server.js

const http = require('http');
const faye = require('faye');

// Create an HTTP server
const server = http.createServer();

// Mount the Faye server at '/faye'
const bayeux = new faye.NodeAdapter({ mount: '/faye', timeout: 45 });

// Attach Faye to the HTTP server
bayeux.attach(server);

// Start the HTTP server
const PORT = 8000;
server.listen(PORT, () => {
    console.log(`Faye server listening on port ${PORT}`);
});
// server.js

const http = require('http');
const faye = require('faye');

// Create an HTTP server
const server = http.createServer();

// Mount the Faye server at '/faye'
const bayeux = new faye.NodeAdapter({ mount: '/faye', timeout: 45 });

// Attach Faye to the HTTP server
bayeux.attach(server);

// Start the HTTP server
const PORT = 8000;
server.listen(PORT, () => {
    console.log(`Faye server listening on port ${PORT}`);
});
JAVASCRIPT

In this instance, an HTTP server listening on port 8000 has the Faye server mounted at /faye. Adapt the port and mount route to the needs of the version of your application.

Client-Side Setup

Add the Faye client library to your HTML page or use a module bundler such as Webpack or Browserify to do so:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Faye Client Example</title>
  </head>
  <body>
    <!-- Include the Faye client script -->
    <script
      type="text/javascript"
      src="http://localhost:8000/faye/client.js"
    ></script>

    Enter the Message: 
    <input type="text" id="messageInput">
    <button onclick="sendMessage()">Send</button>

    <script>
      // Initialize Faye client
      const client = new Faye.Client('http://localhost:8000/faye');

      // Subscribe to a channel
      client.subscribe('/channel', function(message) {
          console.log('Received message:', message);
          // Handle received messages
      });

      // Function to publish a message
      function sendMessage() {
          const message = document.getElementById('messageInput').value;
          client.publish('/channel', { text: message });
      }
    </script>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Faye Client Example</title>
  </head>
  <body>
    <!-- Include the Faye client script -->
    <script
      type="text/javascript"
      src="http://localhost:8000/faye/client.js"
    ></script>

    Enter the Message: 
    <input type="text" id="messageInput">
    <button onclick="sendMessage()">Send</button>

    <script>
      // Initialize Faye client
      const client = new Faye.Client('http://localhost:8000/faye');

      // Subscribe to a channel
      client.subscribe('/channel', function(message) {
          console.log('Received message:', message);
          // Handle received messages
      });

      // Function to publish a message
      function sendMessage() {
          const message = document.getElementById('messageInput').value;
          client.publish('/channel', { text: message });
      }
    </script>
  </body>
</html>
HTML

Adapt the Faye server URL (http://localhost:8000/faye) and the source code and URL of the Faye client script (client.js) to your configuration.

You may effectively add real-time messaging features in your Node.js web application by configuring the Faye package by following these instructions. Modify the examples according to the architecture and needs of your particular application.

Getting started

You'll need to set up a Node.js server to handle Faye connections and PDF-generating requests before you can use IronPDF for dynamic PDF generation and Faye for real-time communications. Here's a detailed how-to:

What is IronPDF?

IronPDF for Node.js is a robust Node.js program designed to convert HTML data into incredibly high-quality PDF files. It speeds up the process of turning HTML, CSS, and other JavaScript files into properly formatted PDFs without compromising the original online content. This is a highly useful tool for web applications that need to produce dynamic, printable documents such as invoices, certifications, and reports.

IronPDF has several features, including customizable page settings, headers, footers, and the option to add fonts and images. It can manage complex styles and layouts to ensure that every test PDF output meets the specifications. Moreover, IronPDF controls JavaScript execution within HTML, allowing for accurate dynamic and interactive content rendering.

faye NPM (How It Works For Developers): Figure 4 - IronPDF

Features of IronPDF

  1. PDF Generation from HTML: Convert HTML, CSS, and JavaScript to PDF. Supports two modern web standards: media queries and responsive design. Handy for using HTML and CSS to dynamically decorate PDF documents, invoices, and reports.

  2. PDF Editing: It is possible to add text, images, and other material to already-existing PDFs. Extract text and images from PDF files. Merge many PDFs into a single file. Split PDF files up into several distinct documents. Add headers, footers, annotations, and watermarks.

  3. Performance and Reliability: In industrial contexts, high performance and reliability are desirable design attributes. Easily handles large document sets.

Install IronPDF

To gain the tools you need to work with PDFs in Node.js projects, install the IronPDF package. Run the following command:

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
SHELL

Combine Faye with IronPDF

Create a rudimentary Node.js server that combines IronPDF for PDF production with Faye for real-time messaging:

// server.js

const http = require('http');
const faye = require('faye');
const IronPdf = require('@ironsoftware/ironpdf');

// Configure IronPDF license (if required)
var config = IronPdf.IronPdfGlobalConfig;
config.setConfig({
    licenseKey: "",  // Set your license key here
});

// Create an HTTP server
const server = http.createServer();

// Create a Faye server
const bayeux = new faye.NodeAdapter({ mount: '/faye', timeout: 45 });

// Attach the Faye server to the HTTP server
bayeux.attach(server);

// Handle Faye client connections
bayeux.on('handshake', function(clientId) {
    console.log(`Client connected: ${clientId}`);
});

// Handle incoming messages for PDF generation
bayeux.on('publish', async function (clientId, channel, data) {
    if (channel === '/generate_pdf') {
        console.log(`Received PDF generation request from client ${clientId}: ${data.htmlContent}`);
        // Generate PDF using IronPDF
        let pdfData = await generatePdf(data.htmlContent);
        var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(pdfData)));
        bayeux.getClient().publish(`/pdf_result/${clientId}`, { pdfData: base64String });
    }
});

// Function to generate PDF using IronPDF
const generatePdf = async (htmlContent) => {
    const pdfDocument = IronPdf.PdfDocument;
    let result = (await pdfDocument.fromHtml(htmlContent));
    const pdfBuffer = await result.saveAsBuffer();
    return pdfBuffer;
};

// Start the HTTP server
const PORT = 3000;
server.listen(PORT, function() {
    console.log(`Server listening on port ${PORT}`);
});
// server.js

const http = require('http');
const faye = require('faye');
const IronPdf = require('@ironsoftware/ironpdf');

// Configure IronPDF license (if required)
var config = IronPdf.IronPdfGlobalConfig;
config.setConfig({
    licenseKey: "",  // Set your license key here
});

// Create an HTTP server
const server = http.createServer();

// Create a Faye server
const bayeux = new faye.NodeAdapter({ mount: '/faye', timeout: 45 });

// Attach the Faye server to the HTTP server
bayeux.attach(server);

// Handle Faye client connections
bayeux.on('handshake', function(clientId) {
    console.log(`Client connected: ${clientId}`);
});

// Handle incoming messages for PDF generation
bayeux.on('publish', async function (clientId, channel, data) {
    if (channel === '/generate_pdf') {
        console.log(`Received PDF generation request from client ${clientId}: ${data.htmlContent}`);
        // Generate PDF using IronPDF
        let pdfData = await generatePdf(data.htmlContent);
        var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(pdfData)));
        bayeux.getClient().publish(`/pdf_result/${clientId}`, { pdfData: base64String });
    }
});

// Function to generate PDF using IronPDF
const generatePdf = async (htmlContent) => {
    const pdfDocument = IronPdf.PdfDocument;
    let result = (await pdfDocument.fromHtml(htmlContent));
    const pdfBuffer = await result.saveAsBuffer();
    return pdfBuffer;
};

// Start the HTTP server
const PORT = 3000;
server.listen(PORT, function() {
    console.log(`Server listening on port ${PORT}`);
});
JAVASCRIPT

Client-Side Setup

Configure Faye on the client side to interact with the server and submit requests for the creation of PDFs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Faye + IronPDF Example</title>
</head>
<body>
    <button onclick="generatePdf()">Generate PDF</button>

    <!-- Include the Faye client library -->
    <script src="https://cdn.jsdelivr.net/npm/faye/browser/faye-browser.min.js"></script>

    <script>
        // Initialize Faye client
        const client = new Faye.Client('http://localhost:3000/faye');

        // Subscribe to receive PDF result messages
        client.subscribe('/pdf_result/*', function(message) {
            console.log('PDF received:', message);
            displayPdf(message.pdfData);
        });

        // Function to request PDF generation
        function generatePdf() {
            // Example: HTML content to generate PDF
            const htmlContent = '<html><body><h1>Hello IronPDF!</h1></body></html>';

            // Send HTML content to server for PDF generation
            client.publish('/generate_pdf', { htmlContent: htmlContent });
        }

        // Function to display the generated PDF
        function displayPdf(pdfData) {
            // Example: Display or download PDF data received from server
            const pdfBlob = new Blob([Uint8Array.from(atob(pdfData), c => c.charCodeAt(0))], { type: 'application/pdf' });
            const pdfUrl = URL.createObjectURL(pdfBlob);
            window.open(pdfUrl, '_blank');
        }
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Faye + IronPDF Example</title>
</head>
<body>
    <button onclick="generatePdf()">Generate PDF</button>

    <!-- Include the Faye client library -->
    <script src="https://cdn.jsdelivr.net/npm/faye/browser/faye-browser.min.js"></script>

    <script>
        // Initialize Faye client
        const client = new Faye.Client('http://localhost:3000/faye');

        // Subscribe to receive PDF result messages
        client.subscribe('/pdf_result/*', function(message) {
            console.log('PDF received:', message);
            displayPdf(message.pdfData);
        });

        // Function to request PDF generation
        function generatePdf() {
            // Example: HTML content to generate PDF
            const htmlContent = '<html><body><h1>Hello IronPDF!</h1></body></html>';

            // Send HTML content to server for PDF generation
            client.publish('/generate_pdf', { htmlContent: htmlContent });
        }

        // Function to display the generated PDF
        function displayPdf(pdfData) {
            // Example: Display or download PDF data received from server
            const pdfBlob = new Blob([Uint8Array.from(atob(pdfData), c => c.charCodeAt(0))], { type: 'application/pdf' });
            const pdfUrl = URL.createObjectURL(pdfBlob);
            window.open(pdfUrl, '_blank');
        }
    </script>
</body>
</html>
HTML

Server-Side: A Faye server (bayeux) is integrated by the Node.js server, which also configures an HTTP server. On the /generate_pdf channel, it watches for incoming messages and client connections. Upon receiving a request for PDF generation, it converts the HTML information supplied to a PDF using IronPDF and returns the completed PDF data as an easy-to-use message to the client.

Client-Side: To obtain the generated PDF data, the browser client creates a Faye connection (client) to the server and subscribes to the /pdf_result/* channel. The "Generate PDF" button causes the user to send an HTML content request to the server, which the server then uses to generate a PDF using client.publish('/generate_pdf', { htmlContent: htmlContent }). It shows or downloads the PDF after it receives the PDF data.

Conclusion

By integrating Faye with IronPDF, a reliable solution for contemporary web applications is offered by combining the benefits of dynamic PDF creation and real-time messaging. Instantaneous client-server communication is made possible by Faye's pub/sub messaging system, which supports applications that need real-time updates such as bug tracker, notifications, and teamwork capabilities. Contrarily, IronPDF enables the programmatic creation, modification, and conversion of PDF documents, enabling the dynamic generation of reports, invoices, and other documents in response to user input or real-time data.

These technologies can be integrated to provide dynamically created material and instant feedback, which can improve the user experience. For example, consumers don't have to wait for a batch process or refresh the website to receive a PDF report request that is processed instantly. Web applications become more responsive and efficient as a result of this smooth interaction, increasing their interactivity and user-friendliness.

By integrating IronPDF and Iron Software, we can add OCR, barcode scanning, PDF output, Excel interaction, and many other functionalities to your Node.js app development toolbox, increasing its usefulness. Iron Software's vast library of community-supported plugins and highly configurable technologies let developers create features and web apps more quickly.

Before deciding to buy, developers can take advantage of IronPDF's many features with a free trial license and a variety of source code samples from the company. See the license page for additional details regarding IronPDF's perpetual licensing. Go to the project documentation page for further details on how to start using IronPDF.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity and problem-solving.

At Iron Software, Darrius enjoys creating new things and simplifying complex concepts to make them more understandable. As one of our resident developers, he has also volunteered to teach students, sharing his expertise with the next generation.

For Darrius, his work is fulfilling because it is valued and has a real impact.

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?