Tag Archives: bower

First few tweaks to default Express app

Every time I create a new Express app, I make sure a few changes to fit my need. In this post, I will focus on starting from scratch on fundamentals towards publishing to Azure.

First of all I create a Node.js app, and install Express.

npm init
npm i --save express
express app-name

To run, simply execute:

npm start

My viewpoint on view engines

I don’t like Jade view engine or any other view engines for that matter in Node.js apps, because to me it’s a overkill, plus there’s not a great deal of tooling support in many cases. I use Visual Studio Code which I think the best slickified code editor I have ever used as I previously have used Brackets and Sublime. Visual Studio Code has the support for super cool Emmet snippets, which allows you to generate tons of HTML code by using simple CSS expressions, although I don’t spend whole day writing a lot of HTML. Here’s an example:

html>head>title{formdata : collect data on all devices}^>body>div.container>div.header

The above CSS expression will generate the following HTML:

<html>
<head>
	<title>formdata : collect data on all devices</title>
</head>
<body>
	<div class="container">
		<div class="header"></div>
	</div>
</body>
</html>

This is not the best example to showcase the true power of Emmet snippets, but you get the idea.

VS Code

Getting rid of the default Jade view engine

I have removed all views/*.jade files and created an index.html instead, and then executed the following to install the ejs view engine instead:

npm i --save ejs

And now I’ve replaced the following line in the index.js / app.js:

app.set('view engine', 'jade');

With the following:

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

Moving routing to another file

The main (index.js/app.js/whatever) js file becomes crowdy very quickly. Therefore, it’s always a best practice to move out the routing code to some other file. I have created framework/routes.js file and moved all the routing code including error handlers like below:

module.exports = function(app)
{
  app.get('/', function(req, res, next) {
    res.render('index', { title: 'Hello World.' });
  });  

  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    res.render('error', {
      message: err.message,
      error: err
    });
    next(err);
  });

  // error handlers
  // development error handler
  // will print stacktrace
  if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: err
      });
    });
  }

  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: {}
    });
  });
};

Now that the routing code is moved, we need to tell the app where to look up once an URL request comes up to the server. That’s a single line hooking:

require('./framework/routes')(app);

Making Bower to work inside public folder

By default, when Bower is installed, bower_components folder will be created at the same level as node_modules which makes it useless for the views, because for the views to use bower_components, it needs to live inside public/views folder. Obviously, bower_components are static resources, therefore, it’s only right to keep it inside public folder because they need no server-side processing. Assuming that Bower was installed and initialized like below:

npm i --save bower
bower init

Now that we have a bower.json file created which is essentially the configuration file for the bower, ignore this. Lets create another file called .bowerrc where we can tell Bower to point to the right folder where we want it to install the components with the following contents, in this case:

{
      "directory": "public/bower_components"
}

Now go ahead and install bootstrap:

bower install bootstrap

You will notice that the bootstrap component was installed inside public folder, now you can go ahead and refer to these resources from your views.

Making it run on Azure

It’s often a painful experience partially due to lack of documentation on how to make Node.js apps run on Azure. You have written a perfectly alright Node.js app and your expectation is that it would run as-is after deploying to Azure, but it wouldn’t. Often times, you will end up with this annoying and at the same time frustrating message: “The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.” or some other HTTP 500 error message. However, there’s a blessing in it. Because it has failed and I will be covering the solution in a bit, it opens up a door to configure Node.js apps in even more ways. Lets take a look.

IIS hosted on Azure has this IIS module installed called iisnode, which facilitates the Node.js runtime. Azure also offers ASP.NET style web.config file to configure a Node.js app. I have created such web.config file and pointed that our entry point for the app should be a server.js file. The following is the web.config which essentially tells IIS to let server.js handle all the dynamic requests and handle the static resources as they are. This contains ton of configurations as comments which you can enable/disable as you see fit for your need:

<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->

<configuration>
     <system.webServer>
          <handlers>
               <!-- indicates that the app.js file is a node.js application to be handled by the iisnode module -->
               <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
          </handlers>
          <rewrite>
               <rules>

                    <!-- Don't interfere with requests for node-inspector debugging -->
                    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
                        <match url="^server.js\/debug[\/]?" />
                    </rule>

                    <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
                    <rule name="StaticContent">
                         <action type="Rewrite" url="public{REQUEST_URI}"/>
                    </rule>

                    <!-- All other URLs are mapped to the Node.js application entry point -->
                    <rule name="DynamicContent">
                         <conditions>
                              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
                         </conditions>
                         <action type="Rewrite" url="server.js"/>
                    </rule>

               </rules>
          </rewrite>
          <!-- You can control how Node is hosted within IIS using the following options -->
        <!--<iisnode
          node_env="%node_env%"
          nodeProcessCommandLine="&quot;%programfiles%\nodejs\node.exe&quot;"
          nodeProcessCountPerApplication="1"
          maxConcurrentRequestsPerProcess="1024"
          maxNamedPipeConnectionRetry="3"
          namedPipeConnectionRetryDelay="2000"
          maxNamedPipeConnectionPoolSize="512"
          maxNamedPipePooledConnectionAge="30000"
          asyncCompletionThreadCount="0"
          initialRequestBufferSize="4096"
          maxRequestBufferSize="65536"
          watchedFiles="*.js"
          uncFileChangesPollingInterval="5000"
          gracefulShutdownTimeout="60000"
          loggingEnabled="true"
          logDirectoryNameSuffix="logs"
          debuggingEnabled="true"
          debuggerPortRange="5058-6058"
          debuggerPathSegment="debug"
          maxLogFileSizeInKB="128"
          appendToExistingLog="false"
          logFileFlushInterval="5000"
          devErrorsEnabled="true"
          flushResponse="false"
          enableXFF="false"
          promoteServerVars=""
         />-->
        <iisnode watchedFiles="*.js;node_modules\*;routes\*.js;views\*.jade"/>
     </system.webServer>
</configuration>

The contents of server.js is extremely simple:

require('./bin/www');

It simply redirects the request to Express. Do you recall when Express was installed it also created a bin/www file where it does the server-side infrastructure handling?

Getting Started with JavaScript-based Full Stack Development

In this post, I have tried to introduce several JavaScript-based development tools with which you can start writing web and mobile apps.

Node.js

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

2000px-Node_js_logo_svg

You can go ahead and install it in your system that will open up a whole new JavaScript-based ecosystem including a nice package management system where you can install/update/uninstall packages including their dependencies from a command-line environment. Because of that, Node.js is also considered this planet’s the ultimate command line tool development platform. Give it a whirl: http://nodejs.org/

Here’s a sample hello world server – think of it as a website that serves itself in response to HTTP requests:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Now in order to run your new Node.js application, here’s the command that you may want to issue, assuming you have saved the file as app.js:

node app.js

This Node.js code opens a server at 1337 port and serves this page when requested at: http://127.0.0.1:1337.

Node.js Package Systems

Node.js allows us to use Node Package Manager (npm) from command line to manage necessary dependencies. Tons of packages can be found from here: https://www.npmjs.com/.

Before we go ahead and install a package we need to create a package.json file which will contain information about our project and will be used to maintain dependencies and their versions. We do not need to create it manually, rather we need to answer a series of questions asked by the following command, which you can just pass entering Enter every time so that it can prepare a set of default settings which is fine for now:

npm init

This will create a package.json file that we had been intending to create. Go ahead and open it – you will find something like as follows:

{
  "name": "nodetest",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "",
  "license": "ISC"
}

Now let us begin with installing the first package. For example: string package offers rich string manipulation features. Let us go ahead and install that:

npm install –g string 
npm install string --save

The first instruction will add the package to the global level, meaning that whenever next time a project would require that the next instruction as above can be issued to retrieve it from the (system-wide) globally available package store stored in your computer. By adding a –save parameter, we are telling that the dependency should be recorded into the package.json as well. Here’s the updated json:

{
  "name": "nodetest",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "string": "^3.0.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "",
  "license": "ISC"
}

Now let’s use the newly added package in the app.js code:

var S = require('string');
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('World exists in the string Hello World: ' + S('Hello World').contains('World'));
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

When hit from the browser, this code will produce the following output:

World exists in the string Hello World: true

Yeoman

Yeoman is a scaffolding tool – what this essentially means is that it can quickly create a boilerplate sample of many JavaScript based libraries/frameworks out there. At the time of typing Yeoman has generators for 1100+ projects. For full reference: http://yeoman.io.

yeoman-logo

I am not a big user of it, however it’s easier to get started on such projects that use full-stack JavaScript technologies. Install Yeoman using the following command:

npm install -g yo

Creating an ASP.NET Web API application using Yeoman

Let us now use the  Yeoman to scaffold an ASP.NET Web API application meaning that it will ask you a series of few questions about your new ASP.NET Web API project and then it will go ahead and create all the directories and files and organize them in order for you to use right away opening up Visual Studio.

npm install -g generator-webapi
yo webapi

Untitled

Creating a Firefox OS app using Yeoman

Here are the set of commands that you can execute:

npm install -g generator-firefox-os  
yo firefox-os

Bower

As you can imagine such JavaScript-based ecosystem comes at a price of plugin management nightmare, however Bower is a yet another tool that aims to solve some of its management problems.

687474703a2f2f692e696d6775722e636f6d2f516d47485067632e706e67

You will be able to find a searchable list of packages here, or you can search from command line as well:

bower search polymer
Search results:

    polymer git://github.com/Polymer/polymer.git
    webcomponentsjs git://github.com/Polymer/webcomponentsjs.git
    polymer-elements git://github.com/Polymer/polymer-elements.git
    ... a big list of polymer related packages ...

Let us create a polymer application which is based on Android’s new Lollypop UI. Much like npm, we need to create a bower.json file using similar command. It will ask a few questions, feel free to answer or leave them.

bower init
bower install -g --save Polymer/polymer

It will create a folder called bower_components where all the plugins will reside and you may refer from your web project. Should you require to update any of the components you may issue the following command:

bower update

Using a package

Let us create a simple HTML page where we will use rickshaw a nice graphing utility. Installing rickshaw:

bower install –g --save rickshaw

Here’s the HTML that renders just nice:

<html>
    <head>
        <link rel="stylesheet" href="bower_components/rickshaw/rickshaw.min.css"/>
        <script src="bower_components/rickshaw/vendor/d3.v3.js"></script>
        <script src="bower_components/rickshaw/rickshaw.min.js"></script>
    </head>
    <body>

        <div id="chart"></div>

        <script>

            var graph = new Rickshaw.Graph( {
                element: document.querySelector("#chart"),
                width: 500,
                height: 200,
                series: [{
                    color: 'red',
                    data: [
                        { x: 0, y: 40 },
                        { x: 1, y: 49 },
                        { x: 2, y: 38 },
                        { x: 3, y: 30 },
                        { x: 4, y: 32 } ]
                }]
            });

            graph.render();

        </script>
    </body>
</html>

Untitled1

By the way, most of these js libraries have really nice mascots/logos. After you have mastered this pattern of development, you can easily dive into many stacks available out there. For example, MEAN = MongoDB + Express + AngularJs + Node.js, CEAN = CouchDB + Express + AngularJs + Node.js and what not. Here’s a guide on how CouchDB + Express + Node.js can play together: CRUD with CouchDB in Node.js, another one tweaking default Express application.