Running QZ-Tray within a function on Express is not possible

I've been working on a web app to print on an LQ-310 Printer using express and QZ-Tray. Unfortunately, I'm facing issues with the printing process - it only prints when users hit the endpoint directly. If I try to encapsulate the QZ-Tray functions within another function, the printing doesn't trigger as expected.

const printInvoice = (req, res) => {
    fs.writeFile(`src/invoice/invoice.json`, JSON.stringify(req.body), (err) => {
        if (err) throw err;
    });

    // shell script to run qz-tray
    const shell = require('shelljs');
    shell.echo('Running qz-tray');
    shell.exec('bash src/invoice/qz-tray.sh');

    fs.readFile(`src/invoice/invoice.json`, (err, data) => {
        if (err) throw err;
        res.json(JSON.parse(data));
    });
}

Despite my efforts, my terminal does not show any results or error messages.

I also attempted to streamline the process by integrating everything into one function within the route, but unfortunately, this did not yield any positive outcomes.

Note: Here is the repository where I am encountering these issues: Rusydy/print-qz

Answer №1

QZ Tray is typically utilized as a client-side library, requiring JavaScript calls to originate from the browser rather than the server.

Below is a basic layout.jade for establishing communication between Express + Jade and QZ Tray, leveraging the express application generator.

  • Note 1: Any novice app design or templating errors in the following content can be attributed to my lack of experience with Express or Jade.

  • Note 2: While Node/server/backend integration with QZ Tray is possible, it is less common compared to client-side implementation.

# ensure qz-tray.js is placed in a publicly accessible directory
curl -o public/javascripts/qz-tray.js https://raw.githubusercontent.com/qzind/tray/master/js/qz-tray.js
doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    /***************************
     * begin code modification here *
     ***************************/ 
    script(src='/javascripts/qz-tray.js', type='text/javascript')
    script.
      qz.websocket.connect().then(() => {
        return qz.printers.find()
      }).then(printers => {
        document.getElementsByTagName("p")[0].innerHTML += "<p>Found printers:</p><ul>";
        printers.forEach(printer => {
          document.getElementsByTagName("p")[0].innerHTML += "<li>" + printer + "</li>";
        });
        document.getElementsByTagName("p")[0].innerHTML += "</ul>";
      });
    /***************************
     *   end of code changes   *
     ***************************/ 
  body
    block content

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to notify a user one minute before their cookie expires using PHP and JavaScript?

I need a solution to alert my logged-in users one minute before their cookie expires, allowing them to save content in the CMS. Any ideas on how I can make this happen? In my auth file, I have configured the following: setcookie("USERNAME", $user,time()+ ...

Remove nested comments using Ajax

I'm encountering a problem while attempting to delete my comments using Ajax. I believe I am on the right track but could use some guidance. Still in the process of familiarizing myself with jquery and similar technologies. While I can remove the comm ...

Save user's email and password for future logins after the initial login

Is there a way to automatically populate the user's email and password in the login form when they check the "remember me" option and return to log in again? This is for a project using React and Next.js. ...

Ways to avoid one session from overwriting another session

I'm currently working on a basic website that requires users to input their email address. However, I've encountered an issue where if I open the webpage in two separate tabs and enter different emails, the second entry always replaces the first ...

How can we configure Node and Express to serve static HTML files and ensure that all requests are routed to index.html?

Currently, I am developing a single-page web application using Node alongside Express and Handlebars for templating. The project is running smoothly with the index.html file being served from a standard server.js script: var express = require('expre ...

Issue with File Input not being validated by Bootstrap Validator

Looking for help with a form field that should only accept .jpg or .png images of a certain file size. The validation doesn't seem to be working when tested with invalid file types. What am I missing? It should function like the example shown here. C ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

The error message "indexOf of undefined" appears when trying to read a property that does not exist within a new

Help Needed: The following error is happening: Cannot read property 'indexOf' of undefined at new HttpRequest (http.js:653) at HttpClient.request (http.js:1069) at HttpClient.get (http.js:1157) This occurs when I use the get() method from Ht ...

Launching a basic Express application on Azure App Service

I am currently facing a challenge with deploying my simple Node/Express app on Azure App Services. The main objective of this endeavor is to enhance my learning by gradually expanding the application using Git and Azure DevOps. Unfortunately, I have hit a ...

implementing a method event within a JavaScript class

Within the wapp.js file, there is a JavaScript class defined as follows: function Wapp() { this.page = function($page_name) { this.onLoad = function($response) { } } this.navigate = { changePage: function(link) { ...

Enhancing web pages using PHP method progress tracking

I am in the process of creating a basic import wizard and I would like to incorporate a notification feature that displays the progress of each method. For example, I have the following methods: public function mainFunction() { $this->firstStep(); ...

Rotating display for showcasing various portfolios

I'm facing an issue with my portfolio images carousel using a map in Bootstrap. When I navigate from one portfolio (e.g. image 4) to another (which has only one image), the carousel shows up blank because the active carousel-item is at index 3 (image ...

Guide to creating 2D point shapes with three.js

Is there a way to render a 2D shape of points in three.js? I have been struggling to find a working geometry for this task. I simply want to create a polygon of points that lie on the same plane. The 'Shape' object doesn't seem to be suitab ...

Unable to submit value on Ajax-powered dynamic select form

I need help with a dynamic Select element inside a form that is not submitting its value. Here is the code snippet: <table> <form> <tr> <td><select>(options values)</select></td> <td id='fill'>< ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

How to use jquery and ajax to retrieve an array of data and show it on the screen

I am facing an issue with my ajax request. Actually, I am unsure of how to fetch multiple records. I attempted the following: $rqt = "SELECT a,b,c from table"; $res = mysql_query($rqt); while ($data = mysql_fetch_assoc($res)): $objet = $d ...

"Upon subscribing, the object fails to appear on the screen

Why is the subscription object not displaying? Did I make a mistake? this.service.submitGbtForm(formValue) .subscribe((status) => { let a = status; // a = {submitGbtFrom: 'success'} console.log(a, 'SINGLE ...

I am struggling to understand how to make use of ajax and php to reload data for pagination

$(function(){ $('.page').click(function() { var paging = $(this).attr("name"); var dataString = 'page='+paging; $.ajax({ type: "POST", url: "<?php echo $backtrack; ?>shop.php", data: dataString, ...

Backend error: Ajax and Node JS not passing parameter values correctly

While developing a web app, I encountered an issue when sending a post request with ajax to a node+express backend. The problem lies in the backend where all parameter values are showing as NULL. I have confirmed this by using console.log(data) on the fron ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...