Tutorial: Full-stack JavaScript for the Enterprise. Getting started with: Ext JS, Node.js, Express, MongoDB and Docker. (2)

Posted on in Docker Ext JS 6 MongoDB Node JS

This is part II of the tutorial, and covers: JavaScript on the server.

Node.js: Setup the back-end with Express 4

Now that the client Sencha app is ready to be served, we need to create our server to display the Sencha app in the browser. What you see in the client folder, those are the development files (classes), which you use on your workstation.

We are going to use Express.js plus a couple of other modules to make our server app, serve pages, so let’s install all those.
(First navigate out the client folder, then..)

client $ cd ../server/
$ npm install --save express compression morgan errorhandler

Now let’s create the following folder structure:

$ mkdir -p config
$ mkdir -p components/errors
$ mkdir views

And the following files:

$ touch app.js
$ touch routes.js
$ touch config/index.js
$ touch config/express.js
$ touch components/errors/index.js
$ touch views/404.html

Let’s look into all the files:

In server/routes.js we define some configuration for the routes, like 404 and other routes.
The file looks like this:

In server/config/index.js we define some common configuration for the server:

And in server/config/express.js we setup Express to serve our files. Note that we point here to the production build of the Sencha app.

In server/components/errors/index.js we define app errors like how 404 should behave and what to respond with.

The server/views/index.html view:




<title>Webservice</title>

Finally the server/views/404.html view:




<title>Oops</title> <h1>404 Not Found</h1>

Now we are ready to start the server:

$ node app.js
Express server listening on 8080, in development mode.

You can now open your browser, the Node server, should serve the production version of your Sencha app. http://localhost:8080.

Before we move on, let’s create a very simple API route, which outputs json data. We will tweak the Sencha client app, so it retrieves the data from Node.

$ mkdir libs
$ cd libs
$ mkdir users
$ cd users
$ touch index.js 

Here’s the contents for the users/index.js file. Like I mentioned before, it doesn’t do anything special then outputting data. But this could be a great point to start for you.

Once you saved this file. We need to create a new route: http://localhost:8080/users/.
We will be able to test this route, when entered in the browser. Node.js needs to be (node app.js).

You can create this file, by opening server/routes.js and add the following route:

  app.route('/users')
    .get(function (req, res) {
        var us = new UsersService();
        us.getData(req, res);
    });

Want to checkout all my code? I hosted it on Github:
https://github.com/savelee/docker-node-server

By the end of this part of the tutorial, you will have a working JavaScript server, created with Node.js and Express. The next part of this tutorial will cover the setup of a MongoDB NoSQL database.

Read the next part

https://www.leeboonstra.com/developer/tutorial-full-stack-javascript-for-the-enterprise-getting-started-with-ext-js-node-js-express-mongodb-and-docker-3/

Tutorial: Full-stack JavaScript for the Enterprise. Getting started with: Ext JS, Node.js, Express, MongoDB and Docker. (1)

Posted on in Docker Ext JS 6 JavaScript Node JS

This is part I of the tutorial, and covers: JavaScript on the client.

Yeah you are correct, when you have a web project, optimized for production, you can use FTP and simple upload the folder on your server. That’s easy, and when you only have a simple HTML5/JS/CSS app, or an application with a PHP back-end on Apache this probably works fine for you. But what, if you have a very complex application, or you are working on an application with a large team? You probably want to automate as much as possible, and make every live build easy.

This tutorial will show you, how you can create an app where we will use JavaScript on the client (an Ext JS 6 app), and JavaScript on the server (Node.js with Express). Maybe you have played around with Node.js before. When you configured a Node.js app with Express etc, you will probably need to install packages via the the NPM packages manager. These are all dependencies. Now imagine you’ve created on your local workstation a fully working back-end, with Node.js and a MongoDB database. You had to install a lot of packages, and make some configurations on your system. This can be a configuration where you save environment passwords, or maybe even hardware configurations.
What you don’t want, is to manually replicate all the settings and configurations you made locally, again on the server. Ideally, you will take whatever you have on your local machine, and take that over. Maybe you even want to run the same operating system and hardware on production. This is where Docker comes into play.

With Docker you can create an isolated container with all the files such as dependencies and binaries for your app to run, making it easier to ship and deploy. It simplifies the packaging, distribution, installation and execution of (complex) applications.
So, what is an isolated container? These containers are self-contained, preconfigured packages that a user can fetch and run with just a single command via the Docker hub (like Github, but for Docker). By keeping different software components separated in containers they can also be easily updated or removed without influencing each other.

About Docker

With Docker you can create an isolated container with all the files such as dependencies and binaries for your app to run, making it easier to ship and deploy. It simplifies the packaging, distribution, installation and execution of (complex) applications.
So, what is an isolated container? These containers are self-contained, preconfigured packages that a user can fetch and run with just a single command via the Docker hub (like Github, but for Docker). By keeping different software components separated in containers they can also be easily updated or removed without influencing each other.

What you will need:

For this tutorial I used: Ext JS 6 and Cmd 6.0.2, Node.js 5.8 with NPM installed and Docker 1.10.

Please install the following:

Ext JS 6: Create the client app

Create the following folder somewhere on your hard drive: dockerextnode.

Put a temporary copy of the Sencha SDK inside dockerextnode, (for example ext-6.0.2). If you don’t have Ext JS yet, feel free to download the trial: https://www.sencha.com/products/evaluate/

Open Windows Command / Terminal, and navigate on the command-line to the dockerextnode folder. From there enter the following commands:

$ mkdir server
$ cd ext-6.0.2
$ sencha generate app Client ../client

You’ve now created 2 folders. The server* folder, which will contain the Node code later and the **client folder, which contains the copy of the Sencha SDK together with a demo app.

Let’s remove the temp folder:

$ cd ..
$ rm -Rf ext-6.0.2

You’ve now removed the temp. Sencha SDK folder. We can now, start testing our Sencha demo app:

$ cd client
$ sencha app build production
$ sencha app watch

This command will spin off, a Jetty server on http://127.0.0.1:1841. Visit this page in the browser, and confirm you see the Sencha demo app. Once, you’ve seen the demo app, we can stop the server, by stopping the sencha app watch (with CTRL + C for example). We will keep the demo app like it is, but this could be a nice starting point for you, when you want to create your own app.

NOTE:
By default, the sencha app watch command starts the development server on the internal IP at port 1841. If you want to change the server’s port, for example to port 8082, you will have to start the server via the web command. This command will only bootu p an internal server, and won’t “watch” your app for changes. $ sencha web -port 8082 start

Want to checkout all my code? I hosted it on Github:
https://github.com/savelee/docker-ext-client

By the end of this part of the tutorial, you will have a working JavaScript client app, created with Sencha Cmd and Ext JS 6. The next part of this tutorial will cover the setup for creating a Node.js with Express app.*

 

ExtJS6-demo-app

Read the next part

https://www.leeboonstra.com/developer/tutorial-full-stack-javascript-for-the-enterprise-getting-started-with-ext-js-node-js-express-mongodb-and-docker-2/

How to generate a PDF from an Ext JS app

Posted on in Environment Ext JS Ext JS 5 Ext JS 6 Node JS

Often I get the question if it’s possible to generate a PDF from a Sencha app. Well yes that’s possible, but not with Ext JS code only. Though, Ext JS has an exporter, to export grid/pivot data into an XML or Excel file, and you can export charts to images. Out of the box we can’t generate PDFs from full Sencha apps, with the framework.

What you will need is an additional script, often these solutions are handled on the backend, but there are also solutions which can do this client-side.

To name few, see the list below. I didn’t use them all. But I’ve done it before on the client-side with JavaScript, with PHP and back in the days also once in Java.

Nowadays, I love Node JS! So I’ll show you how I recently created a generator with JavaScript for NodeJS and PhantomJS. PhantomJS?PhantomJS is a headless Webkit browser formerly written by (ex Sencha employee) Ariya Hidayat. You will need to install PhantomJS on your environment, but once installed you can run PhantomJS from your command-line. Why is this so powerful? Well you can use it, to:

  • Headless website testing
    Run functional tests with frameworks such as Jasmine, QUnit, Mocha, Capybara, WebDriver, and many others.
  • Page automation & screenscraping
    Access and manipulate webpages with the standard DOM API, or with usual libraries like jQuery.
  • Network monitoring
    Monitor page loading and export as standard HAR files. Automate performance analysis using YSlow and Jenkins
  • Screen capturing
    Programmatically capture web contents, including SVG and Canvas. Create web site screenshots with thumbnail preview etc

The last usecase, is where I am using it for. To let PhantomJS visit my Ext JS app, and capture the screen, by generating it to a PDF. You can run a working example via this URL: http://ladysign.nl/pdfgenerator?page=https://www.leeboonstra.com/senchaplaces (I’m creating a PDF of this simple Ext app.)

Nice to know, Sencha is using PhantomJS inside Sencha Cmd, for example we use it to generate images from CSS3 features that aren’t supported in legacy browsers and recently we compile Sass stylesheets with JavaScript, to production ready CSS (Fashion). How did I do this?

  1. Let’s say you have an environment with Node JS and a web server with Express installed, how can you make a PDF from an Ext JS app? I’m not an Node/PhantomJS expert, but I can show you some simple steps, which you can do too!

    You will need to create a route that listens to an URL that should invoke PhantomJS. For example:

    var PdfHelp = require('./libs/pdfgenerator-help');
    router.get('/pdfgenerator/', function(req, res){
        var pdf = new PdfHelp();
        pdf.generatePdf(req, res);
    });
    
  2. On your environment (dev and production), you will need to install PhantomJs, you can install it via the npm package manager: npm install phantomjs -s

    Once it’s installed, you can run PhantomJS JavaScript pages, by running: phantomjs scriptname.js from the command-line.

  3. I created a simple helper script which can listen to an argument that passes in a URL of my Sencha app. This probably doesn’t make much sense for your own app, but you will get the idea on how to do this.

    I use a Node child process, to execute PhantomJS from my environment. It passes in two arguments; the phantomjs script to execute (generate.js - see below), and in my case the URL to the Sencha app.

    var path = require('path');
    var childProcess = require('child_process');
    var phantomjs = require('phantomjs');
    var binPath = phantomjs.path;
    var childArgs = [
        path.join(__dirname, 'phantomjs-script.js'),
        'some other argument (passed to phantomjs script)'
    ];
    
    childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
        // handle results
    });
    

    You can find my code here

  4. Here’s the phantomjs generate script that I used:

    What’s important to know:

  5. The big magic trick here, is that you’ll need to wait till the headless browser loaded the Sencha app with the framework completely in its memory. Otherwise you would print an empty page, (because index.html files in Sencha apps are usually pretty empty, since Ext JS generates the browser DOM elements).

    Take a look into the waitFor() method I used. The first argument is a test function. This test function, (see line 94), tries to find the Ext namespace in my Sencha app. When it’s there, I still don’t want to immediately make the screenshot, because maybe my stores are not loaded yet. So I wrote another evaluation: Ext.ComponentQuery.query('grid')[0].getStore().count(); If there is data in my store, then go ahead and generate the PDF.

    Again, this probably doesn’t make sense for your application, but you will get the idea.

  6. You render the page with page.render('my-pdf-name.pdf'); and then you exit the phantomjs process ( phantom.exit()).

  7. Back into my PDF helper class, I wrote the following lines, to set the filename of the PDF and directly open it in my browser. It’s important that you set the page headers and content type to application/pdf:

    var filename = "test.pdf";
    filename = encodeURIComponent(filename);
    
    res.setHeader('Content-disposition', 'inline; filename="' + filename + '"');
    res.setHeader('Content-type', 'application/pdf');
    
    var fs = require('fs');
    fs.readFile(filename, function(err,data) {
            res.contentType("application/pdf");
            res.end(data);
    });
    

And that’s it! As you can see when using PhantomJS for visiting your Sencha app, you might want to deal with the timing issues. As by default the index.html in a Sencha app is empty, and a Sencha app is generated in the DOM.

There are lots of ways on how you can create PDFs or images from Sencha apps. Which technologies and tricks did you use?

Update:

Ext JS 6.2 Premium, ships with a data exporter package for grids and pivot grids. It will be possible to export all the records which are visible in a grid to: XML, CSV, TSV, HTML and Excel format. Shikhir Singh, lately wrote a nice post about; how to extend from Ext.grid.plugin.Exporter to easily export to PDF.https://www.sencha.com/blog/exporting-data-from-an-ext-js-grid-to-pdf/