Let's build a PDF Report builder using just NodeJS
Posted on August 14, 2017
NodeJS as Windows Service
Let's build a PDF Report builder using just NodeJS
Posted on August 14, 2017
Recently I was given a task of writing a PDF Reporting solution. I ended up writing everything using Crystal Reports, due to business reliance but started with NodeJS as Windows Service setup.
My thoughts and requirements:
should be easy to update for ‘future devs’ so picked Javascript
should be easy to support so a Windows service sound like a good idea (easy to check if it’s running, can be restarted)
As I like Node.js I started looking for modules and straight away found:
handlebars-pdf module
node-windows module
As you can expect the first one builds PDF reports and it’s really easy to use especially when combined with mssql (module responsible
for connecting with MS SQL instances and running stored procs). The second one is able to run your Node.js as a Service! How cool is that!
I started with Node.js installation, this can be done using an executable file which can be downloaded from Node js website.
Then:
Afterwards I generate an app with Pug template engine (I won’t need it but just in case as default Jade is not supported anymore):
Then enter the directory:
Install node-windows according to the instructions:
And:
Node Windows is now installed! Let’s create a Windows service:
Default Express setup is in the bin directory in the www file. Taking this into account we can create the install Service script service.js in the bin directory:
I open the VS Code Terminal, enter the bin directory and:
You can do the same by using Command Prompt or Powershell.
Go to Services and there it is, your own Windows Service running your app! Go to the browser and open localhost:3000 or http://127.0.0.1:3000 if you haven’t changed the default port.
Now the fun part begins. Install handlebars-pdf using npm and add this script to app.js:
OK. So I did all that and nothing! It works when you run it locally using node but not from the service… Luckily the node-windows module adds a daemon folder in the directory from which you run the service.js file (bin in our case) where we can find an error file.
But what does the above tells us? Apart that the error happens in html-pdf module (a handlebars-pdf dependancy) not much. Luckily I’ve found this gem!
https://stackoverflow.com/questions/37856247/html-pdf-not-creating-file-on-iis-server-with-node-js - It says that 2.0.1 fails but 1.5.0 is working fine! Let’s try that!
We run:
Restart the service and success! We have a Windows service which we can start, stop, restart, write a batch file to manage so our Dev-Ops can manage it remotely and let us work using JS we love!
I didn’t have too much time but this is how you’d run a stored proc using mssql module to pull data out of a SQL Server: