Asynchronous JavaScript: Promises

Posted on in Ext JS 6 Uncategorized

JavaScript is single threaded, causing code to execute from top to bottom, so two bits of code cannot run at the same time. For example, you might download a JSON file from an (external) server and you’d have to wait until you retrieve that file. Instead of blocking the thread, there are ways you can streamline this code execution by using asynchronous JavaScript.

You’re probably already familiar with asynchronous JavaScript. Events (observer pattern) and Callbacks are examples of asynchronous code. For example, whenever you make an Ext.Ajax request or a user presses a button, the action is pushed into a queue, which is called the event loop. The JavaScript engine doesn’t start processing the event loop until the code has been executed after an async function (from top to bottom). This means that JavaScript code is not multi-threaded even though it appears to be so.

Event Loop

Callbacks are often used when you have an async operation (for example, loading data from a database) that should notify the caller about its completion. When calling such a function, you can pass it another function as an argument, which confirms that something has happened. Putting callbacks into callbacks is a great solution, and I think that’s one of the powerful features of JavaScript. However, it can be messy when your code requires other asynchronous pieces of code first.

For example, you read your user settings from local storage (that’s a callback!). Based on those settings, you make a request from some external server with a database connection, (that’s callback #2). Before you render that information on the screen, you retrieve something else from the database (that’s callback #3).

These steps are very common when you build a large enterprise app. In your code, there will be a callback function, written in a callback function, that’s in another callback function. You can imagine if these functions are spread over separate files that you’d have a hard time reading this code back a month later.

This is where JavaScript Promises comes into play. It’s a new way of writing your code in a more readable and understandable way. A Promise represents the result of a task, which may or may not have been completed. Like a contract for a value that we might not know when the promise is created. It’s an object or function with a then method. Because of the “then” method, the action can be chained endlessly, and that’s awesome!

A Promise typically has one of these 4 states.

  • fulfilled – when the promise succeeds
  • rejected – when the promise failed
  • pending – ongoing, hasn’t been fulfilled or rejected yet
  • settled – it has been fulfilled or rejected already

JavaScript Promises

Promises is part of ECMAScript 6, which is available in the client of some modern browsers, and also within the latest version of Node.js. The following browsers do not support JavaScript Promises: Explorer 11 and below, Android 4.4 and below, and iOS Safari 7.1 and below.

Ext JS 6 supports Promises and conforms to the Promises A+ spec; both Classic and Modern toolkits are included. You can call the Sencha Promises class, which is a wrapper for the native JavaScript functionality. Legacy browsers will use the fallback provided by Sencha, and modern browsers will use the native functionality.

Here’s an example of a function that returns a Sencha Promise object:

requestUserSettings: function(){
        return new Ext.Promise(function (resolve, reject) {
            //something asynchronous, like loading a store
            Ext.getStore(‘Settings’).load({
                callback: function(records, operation, success) {
                        if(success){
                            if(records.length > 0){
                            //when it’s ok
                                resolve(records);
                            } else {
                            //still ok, but no results
                                resolve(false);
                            }
                        } else{
                        //something bad happened
                            reject(operation);
                        }
                  }
            });
        });
}

The Ext.Promise constructor takes one argument, a callback with two parameters, resolve and reject. When it does something asynchronous within the callback, like retrieving user settings from a local storage store, then it calls “resolve”; if everything worked it passes in the result, otherwise it calls “reject” and passes in what went wrong.

Here’s how you use that Promise:

this.requestUserSettings().then(function(records) {
  //It’s ok. do something with the records
}, function(err) {
  //oh no, something went wrong, display a nice error
});

The “then” takes two arguments, a callback for a success case, and another one for the failure case our website. Both are optional, so you can add a callback for the success or failure case only. You can chain as many then methods as you want to run additional async actions one after another.

Besides the “then()” instance method, there are also ways to terminate a Promise chain (“done()”), cancel pending chains (“cancel()”). Also, there’s a way to attach an onCompleted callback to the chain (“always()”), for example with cleanup logic regardless the outcome. And, you can attach an onRejected callback, if one action within the chain is rejected (“otherwise()”), for example to handle failures.

In addition to Ext.Promise, Sencha will also ship Ext.Deferred, which is a mechanism used to create new Promises within Ext JS 6. The difference between these two constructors is that with a deferred constructor the creator has direct access to “behind the scenes” extras, such as progress updates.

Last but not least, Sencha integrated Promises support into Ext.Ajax.

Ext.Ajax.request() is now an instance of a class derived from Ext.data.request.Base which can be used with a then method. It allows you to write code like this:

Ext.Ajax.request({
    url: 'feed.json',
}).then(function(response) {
    // use response
}).always(function() {
   // clean-up logic, regardless the outcome
}).otherwise(function(reason){
   // handle failure
});

More Resources

There’s a lot more information to explain how you can use JavaScript & Ext JS Promises. Take a look at these resources to learn more!

Connect & play around with BB-8 by Sphero with JavaScript on a Mac

Posted on in JavaScript Robotics

I'm a huge Star Wars fan, and like most of you, i've seen The Force Awakens as well. I immediately felt in love with BB-8. The little white orange droid.
So you can imagine, how happy I was, when I opened my christmas presents, and found the little BB-8 by Sphero droid in a box.

BB-8 by Sphero, is a little toy robot that you can control with apps for Android and iOS, via bluetooth. Actually the sphere is the true robot, BB-8's head is attached to the big sphere, via a magnet, and it has little wheels so it always stays on top, and gives it the Looney Toones Road runner look, while rolling. Cute.

This little droid has the following functionalities; it can roll around (quiet fast,), it can listen to your voice (via the app), it can show colors, it has IMU, 3 axis accelerometer, 3 axis rotation gyro and locator sensors.
The BB-8 uses a Bluetooth Low Energy (LE) interface, also known as "Bluetooth Smart" or "Bluetooth 4.0/4.1". What's really awesome is that Sphero opens up their APIs, so developers like me, can play around with this. And that's great.
There are SDKs for Android, iOS, Windows development, and there's a JavaScript SDK!

Since I'm a JavaScript lover, I thought, let's give it a go, and try this out myself. Here's are the steps that I took, to get it all up and running.

I tried it on a Mac OSX with XCode installed. You will need an editor and Node JS on your machine. With these base requirements, you will need to install the Sphero SDK, and also Noble, a hardware adapter that supports the Bluetooth 4.x+ standard to connect your computer to your BB-8. https://github.com/sandeepmistry/noble
With Noble, you can read out the bluetooth information, which you will later need while writing your code.

To get Noble up and running I had to fix my system paths. I've added the following to my bashprofile, to make sure Noble and XPC-Connection which is what the package uses under the hood, don't run into build errors:

export MYBIN=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
export PATH=${MYBIN}:${PATH}

Then afterwards, run the following commands to make a connection from your computer:

The UUID is what you'll need. I wrote this simple script, which I run in Node to make a simple connection with my little friend, and read out his information:

It doesn't do anything special yet, other than switching some colors, but this is a great start. My next goal will be to create my own Sencha universal app, to control BB-8 via a web interface. I'll need a Node JS Express back-end for that: Once, I'm done with that I can share this, in another blog post, but here's a start:
https://github.com/savelee/bb8-starwars

For now, take a look into these resources:

My SenchaCon introduction

Posted on in Sencha

On April 7-9 in the heart of Silicon Valley at the Santa Clara Convention Center, Sencha is organising a huge developer conference. It’s going to be three days jam packed with nearly 50 technical sessions led by Sencha engineers, partners and key customers. - Register today! Save 20% off the price with discount code: LeeBoonstra.
SenchaCon.com

SenchaCon 2015 Lee Boonstra introduction! from Lee Boonsta on Vimeo.

Sencha Cmd for scaffolding Sencha Touch / EXT MVC project

Posted on in Environment Sencha Touch

Sencha's commandline tools (Sencha CMD) previous known as Sencha SDK Tools are really great! With one line in your terminal you can generate your MVC boilerplate.
From scaffolding a new project, to minifying and deploying your application to production, Sencha Cmd provides a full set of lifecycle management features to compliment your Sencha project.

First start downloading the Sencha CMD: http://www.sencha.com/products/sencha-cmd/download
Run the installer and remember the path where it's installed.

Let's start generating a MVC project for Sencha Touch. (You can use the same instructions for an EXT JS4 project btw, use the EXT library instead):

  1. Now open your terminal on Mac OSX (or Run > CMD on Windows).
  2. Test with the command: sencha if Sencha CMD is correctly installed.
    It should prompt you all the Sencha options & commands.
  3. Incase you don't see anything, you need to make sure sencha is added to the classpath.
    (On Mac OSX you can change this by opening, .bash_profile in your user folder. (hidden file). Add the following line: export PATH=/Users/username/bin/Sencha/Cmd/3.0.0.250:$PATH)

(Incase you don't have Sencha Touch yet, download it here and extract it in your project directory.)
4. Create a project folder. (for example MyApp)
5. Now let's start:
A. You have to be in the folder where Sencha Touch 2 is extracted.
B. Type the following command sencha generate app MyApp [path]
C. The MyApp name will be the name of your app, (note: this will be the App namespace later)

The command could look like this:

MyMacBookPro:touch2 lee$ sencha generate app MyApp XAMPP/htdocs/

Great, so now that you have a project, let's generate a model:
Specify the model name, and all the fields.

sencha generate model -name MyModel -fields fName,lName

Generate a form:

sencha generate form -fields [comma delimited list of fields] -name formName 

As you can see, you can almost generate everything.
To see an overview of what else you can generate type the following command:

sencha help generate

Always use semicolons in JavaScript

Posted on in JavaScript

According to Javascript; the semicolon after a statement (for example a function), is optional.
However, it's much better to end your line with a semicolon. A validator like JSLint for example, will throw a warning, even though
the browser won't and accepts it.

See below, which strange things can happen when you won't end your line with a semicolon.
Javascript errors because of the order of javascript functions mixed with jQuery plugins...
http://jsfiddle.net/bpsuW/11/

foo is a simple javascript function.
Baz is a simple self running jQuery plugin. (because of the parentheses surrounding it).

foo = function(){
alert("function 1"); 
}

(function(){
$.fn.Baz = function(opt){
alert("function 2");
}
})(jQuery)

See below the script, without strange javascript errors.
http://jsfiddle.net/bpsuW/10/

The answer is really logical.
Because there is no semicolon, the jQuery plugin (Baz) will directly execute, because of the parentheses.
Like it's a parameter of the javascript function you wrote before. (foo), and then throws errors.
So:

foo(Baz)

When you mix your jQuery plugins with native javascript classes and functions in different orders; these kind of errors can happen.
This scenario above shows you why you should always end your statements with a semicolon.

viagra for sale viagra dosage viagra alternatives how does viagra work cyalis generic cialis cialis for sale cialis coupons side effects of viagra viagra pills for sale viagra prices without insurance cialis generic cialis pills for sale viagra savings offer viagra canada canada viagra over the counter viagra cialis cialis side effects generic for cialis cialis sample viagra coupons 75 off cialis 20mg is viagra covered by insurance online viagra viagra substitute cialis without a doctor's prescription buy cialis female viagra cialis 5mg daily free cialis viagra vs cialis vs levitra viagra coupons canada cialis cialis 5 mg cialis savings card cialis coupon cialis dosage recommendations viagra government funding generic levitra levitra vs cialis pfizer viagra coupons utilisation viagra cialis trial sildenafil vs viagra levitra vs viagra for hardness 200 cialis coupon online cialis how much does cialis cost cialis copay card cialis dosage strengths levitra online cialis coupons 2017 cilias cialis effects daily cialis inexpensive viagra pills cost of cialis levitra women viagra generic viagra 100mg how much does viagra cost levitra 10 mg cialis cheap viagra single packs cost natural viagra buy viagra cialis otc cvs pharmacy viagra coupons walgreens viagra substitute viagra vs cialis cialis coupons printable levitra coupons free viagra stendra vs viagra cialis coupons from manufacturer cialis voucher levitra 10mg viagra from amazon buy viagra online levitra without a doctor prescription cialis free trial levitra vs viagra trial viagra sample canadian cialis is viagra government funded in america viagra pill cialis from canada cialis professional otc viagra levitra coupon cialis coupon print cialis pills cialis vs viagra levitra generic what is levitra viagra cialis cialis discount wholesale cialis viagra prices erectile dysfunction cialis sex viagra for women side effects of cialis does the government fund viagra cialis testimonials viagra coupons from pfizer cialis canada viagra single packs cialis generic availability cialis patent expiration date extended cialis samples overnight cialis for bph pfizer viagra lowest cialis prices cost of viagra levitra prices how long does levitra last generic for viagra female viagra pills viagra without a doctor prescription usa cialis on line generic cialis tadalafil cialis coupon 20 mg viagra discount viagra viagra generic cialis patent expiration viagra activate non prescribed viagra viagra coupon cialis canadian pharmacy buy levitra levitra vs viagra viagra on line revatio vs viagra is viagra federally funded cialis vs viagra levitra reviews viagra pills liquid cialis cialis medication generic cialis at walmart 9 levitra at walmart cialis dosage cealis viagra patent expiration discount cialis viagra 100mg price walmart buy cialis online cialis for daily use cialis samples viagra vs cialis cost of levitra how to take cialis what does viagra do cialis website viagra price viagra for women cialis prices does viagra work cialis 5mg viagra without prescription viagra side effects levitra loc us viagra porn levitra side effects viagra without a doctor prescription canadian viagra cialis daily viagra cost viamedic cialis cialis 30 day sample levitra dosage price cialis levitra 20 mg sophia viagra what is viagra when will cialis go generic how long does viagra last cialis generic tadalafil levitra cost buy levitra online cialis or viagra cialis reviews cialis cost viagra best price generic viagra where to buy viagra viagra samples viagra pharmacy cialis or viagra order online viagra viagra costs cialis alternative cialis 30 day trial coupon viagra dose viagra on line no prec cialis 10 mg is viagra government funded cialis pharmacy prices generic viagra available in usa levitra 20mg how does cialis work natural viagra alternatives that work cialis 20 mg cialis 20mg directions viagra 100mg tablets retail price cialis for men cheap viagra cialis online healthy man viagra levitra canada viagra sex viagra from canada is viagra funded by government viagra girls cialis pricing herbal viagra cialis price cialas cialis tadalafil viagra online cialis for women cialis patent expiration 2017 best price viagra what is cialis cheap cialis levitra 20 mg cost walmart viagra government funded viagra ingredients viagra vs cialis vs levitra

Make your mobile webapp work offline with application cache

Posted on in Mobile

This tutorial will help you to put your mobile webapp offline.

1. create your cache manifest file
create a file yourappname.manifest in your application root.
In the file enter all files you have to cache to make your app working offline.

For example the app.manifest file looks like this:

CACHE MANIFEST
#rev2

# Explicitly cached entries
CACHE:
index.html

img/icon.png
img/phone_startup.png
img/tablet_startup.png
img/main-image.png

css/ext-touch.css
css/default.css

js/ext-touch-debug.js
js/ext-touch.js
js/index.js

# Resources that require the user to be online.
NETWORK:
js/twitter.js

#If source in inaccessible serve other file. for example: /index.php /index.html
FALLBACK:

2. Add your manifest to your application .html file header
In your html file:



3. Create a .htaccess file and add expire configuration for your *.manifest file to your app root.


ExpiresActive On
ExpiresDefault "access"

4. Add type manifest to your apache config (apache.conf / vhost.conf or .htaccess file)

AddType text/cache-manifest .manifest

That's it, now your app should work offline. You should know that, as soon as the manifest file fails with caching the files. It stops. That means that the files will not be updated.

Use this code to check/swap cache via code:

var i = -1;

// Convenience array of status values
var cacheStatusValues = [];
cacheStatusValues[0] = 'uncached';
cacheStatusValues[1] = 'idle';
cacheStatusValues[2] = 'checking';
cacheStatusValues[3] = 'downloading';
cacheStatusValues[4] = 'updateready';
cacheStatusValues[5] = 'obsolete';

// Listeners for all possible events
var cache = window.applicationCache;
cache.addEventListener('cached', logEvent, false);
cache.addEventListener('checking', logEvent, false);
cache.addEventListener('downloading', logEvent, false);
cache.addEventListener('error', logEvent, false);
cache.addEventListener('noupdate', logEvent, false);
cache.addEventListener('obsolete', logEvent, false);
cache.addEventListener('progress', logEvent, false);
cache.addEventListener('updateready', logEvent, false);

// Log every event to the console
function logEvent(e) {
i=i+1;
var online, status, type, message;
online = (isOnline()) ? 'yes' : 'no';
status = cacheStatusValues[cache.status];
type = e.type;
message = 'online: ' + online;
message+= ', event: ' + type;
message+= ', status: ' + status;
if (type == 'error' && navigator.onLine) {
message+= ' There was an unknown error, check your Cache Manifest.';
}
log(i + ' ' + message);
}

function log(s) {
//alert(s);
console.log(s);
}

function isOnline() {
return navigator.onLine;
}

if (!$('html').attr('manifest')) {
log('No Cache Manifest listed on the tag.')
}

// Swap in newly download files when update is ready
cache.addEventListener('updateready', function(e){
// Don't perform "swap" if this is the first cache
if (cacheStatusValues[cache.status] != 'idle') {
cache.swapCache();
log('Swapped/updated the Cache Manifest.');
}
}
, false);

// These two functions check for updates to the manifest file
function checkForUpdates(){
cache.update();
}
function autoCheckForUpdates(){
setInterval(function(){cache.update()}, 10000);
}

More info's, can be found here:
http://developer.apple.com/library/safari/#documentation/iPhone/Conceptual/SafariJSDatabaseGuide/OfflineApplicationCache/OfflineApplicationCache.html

viagra canada cialis dosage recommendations cost of cialis cilias cialis price cvs pharmacy viagra coupons revatio vs viagra cialis 30 day trial coupon cialis coupons from manufacturer levitra vs viagra for hardness cialis medication non prescribed viagra viagra on line no prec cialis cheap viagra for women levitra generic viagra prices viagra single packs cost viagra vs cialis online cialis cialas viagra porn cialis patent expiration 2017 cialis daily natural viagra how to take cialis cialis sample levitra coupon cialis cost levitra loc us side effects of viagra generic for cialis how does viagra work viagra substitute price cialis viagra activate sildenafil vs viagra erectile dysfunction cialis levitra 10mg viamedic cialis cialis alternative viagra vs cialis vs levitra utilisation viagra what is levitra cheap cialis viagra coupons 75 off generic cialis at walmart cialis vs viagra cialis patent expiration date extended viagra dosage is viagra funded by government viagra girls cialis 5mg women viagra cialis 20mg cialis dosage cialis from canada pfizer viagra coupons discount viagra lowest cialis prices viagra pills for sale best price viagra viagra dose levitra cost how much does viagra cost viagra coupon cost of viagra what does viagra do buy viagra female viagra 9 levitra at walmart free viagra order online viagra 200 cialis coupon cheap viagra cialis pills buy viagra online free cialis is viagra federally funded cialis vs viagra cialis coupon cialis coupons is viagra covered by insurance levitra coupons what is cialis cialis without a doctor's prescription levitra prices viagra from amazon levitra viagra from canada generic viagra available in usa what is viagra viagra government funding cialis website how long does levitra last viagra side effects cialis voucher viagra savings offer buy cialis viagra patent expiration viagra generic cialis for women sophia viagra viagra coupons viagra vs cialis cialis pricing cialis coupon 20 mg how long does viagra last viagra sex where to buy viagra cialis otc cialis coupons printable levitra without a doctor prescription cialis canada levitra 20 mg herbal viagra levitra vs viagra cialis or viagra levitra side effects levitra canada does viagra work pfizer viagra wholesale cialis buy cialis online how does cialis work cialis coupon print viagra pills generic cialis tadalafil viagra cialis cialis for daily use viagra pharmacy does the government fund viagra cialis copay card viagra prices without insurance levitra dosage cialis professional cialis samples viagra 100mg price walmart natural viagra alternatives that work healthy man viagra cialis savings card trial viagra sample cialis or viagra how much does cialis cost cialis coupons 2017 side effects of cialis viagra on line viagra cost generic levitra levitra vs viagra cost of levitra cyalis cialis dosage strengths when will cialis go generic is viagra government funded buy levitra viagra alternatives cialis 5 mg cialis for sale buy levitra online cialis discount cialis testimonials viagra generic viagra viagra for sale viagra samples cialis 20mg directions liquid cialis cialis free trial cialis canadian pharmacy sex viagra for women over the counter viagra viagra 100mg tablets retail price discount cialis viagra best price viagra without a doctor prescription usa otc viagra viagra ingredients generic for viagra walgreens viagra substitute cialis prices levitra online canadian viagra canadian cialis levitra 20 mg cost walmart viagra vs cialis vs levitra female viagra pills daily cialis cialis cialis pharmacy prices cialis generic cialis generic availability levitra 20mg levitra 10 mg levitra reviews viagra single packs cialis 30 day sample cialis tadalafil viagra without prescription cialis for bph cialis samples overnight levitra vs cialis cialis 5mg daily cialis effects generic viagra 100mg online viagra cialis pills for sale viagra government funded cialis on line cialis trial generic cialis viagra pill cialis 20 mg viagra online inexpensive viagra pills cialis side effects viagra costs viagra price viagra coupons from pfizer cialis reviews cealis is viagra government funded in america stendra vs viagra viagra without a doctor prescription cialis 10 mg cialis patent expiration canada cialis cialis for men cialis online cialis generic tadalafil canada viagra

Node Connect example

Posted on in JavaScript Node JS

The example below can be easily replaced with Node Connect. Just with a few lines.
app.js

var http = require('http');
var path = require('path');
var fs = require('fs');
var extensions = { 
   ".html" : 'text/html', 
   ".css" : 'text/css', 
   ".js" : 'application/javascript',
   ".json" : 'application/javascript', 
   ".png" : 'images/png', 
   ".gif" : 'images/gif', 
   ".jpg" : 'images/jpeg' 
} 

http.createServer(function(req, res){ 
   var filename = path.basename(req.url) || 'index.html', 
      ext = path.extname(filename), 
      dir = path.dirname(req.url).substring(1), 
      localPath = __dirname + "/views/"; 

     //console.log(localPath); 
     if(extensions[ext]){
        localPath += (dir ? dir + "/" : "") + filename; 
        path.exists(localPath, function(exists){ 
           if(exists){ 
              getFile(localPath, extensions[ext], res) 
           } else { 
              res.writeHead(404); res.end();
           } 
        }); 
     }
}).listen(8000, '127.0.0.1'); 

getFile = function(localPath, mimeType, res){ 
   fs.readFile(localPath, function(err, contents){ 
   if(!err){ 
      res.writeHead(200, { 
         "Content-Type" : mimeType, 
         "Content-Length" : contents.length 
      }); 
      res.end(contents); 
   } else { 
      res.writeHead(500); 
      res.end(); 
   } 
});

Now install Connect:

$ sudo npm install connect

app.js

var connect = require("connect");
connect().use(connect.static(__dirname + "/views")).listen(8000);

cialis pills for sale levitra generic levitra 20 mg cialis vs viagra levitra vs cialis what is cialis viagra from canada how does cialis work cialis daily cheap cialis how long does levitra last cialis 5mg daily pfizer viagra coupons cialis dosage levitra reviews is viagra government funded in america revatio vs viagra how to take cialis viamedic cialis cialis testimonials is viagra funded by government discount cialis viagra vs cialis vs levitra viagra price levitra 20 mg cost walmart cialis cheap cialis vs viagra levitra loc us cialis online canada viagra viagra pill free viagra generic cialis at walmart non prescribed viagra viagra single packs cost viagra best price viagra without prescription buy viagra viagra sex viagra online cialis from canada viagra 100mg price walmart viagra on line no prec inexpensive viagra pills levitra vs viagra buy cialis online viagra pharmacy cialis effects cialis free trial cialis pharmacy prices levitra 20mg cialis medication viagra vs cialis cialis canadian pharmacy cialis price natural viagra viagra prices without insurance levitra prices cialis on line best price viagra viagra coupons from pfizer cialis coupon 20 mg cealis cialis discount cialis coupons 2017 levitra 10mg generic levitra cialis reviews viagra cost cyalis sophia viagra lowest cialis prices levitra cost cialis 20 mg cost of levitra cvs pharmacy viagra coupons buy levitra cialis 10 mg canadian viagra cialis generic online viagra buy viagra online viagra for women cialis patent expiration 2017 cialis 5mg levitra without a doctor prescription viagra cheap viagra what does viagra do levitra vs viagra canadian cialis healthy man viagra is viagra covered by insurance viagra generic cialis 20mg viagra vs cialis vs levitra viagra coupons 75 off cialis 20mg directions cialis patent expiration cialis dosage strengths cialis dosage recommendations viagra side effects cialis or viagra cialis for men discount viagra does the government fund viagra sildenafil vs viagra sex viagra for women levitra viagra on line buy levitra online viagra substitute how much does viagra cost levitra 10 mg cialis coupon print female viagra erectile dysfunction cialis levitra online side effects of viagra viagra coupons side effects of cialis utilisation viagra viagra government funded canada cialis cialis patent expiration date extended herbal viagra women viagra cialis canada buy cialis cialis generic viagra 100mg viagra pills cialis coupons viagra alternatives levitra coupons cialis side effects cialis voucher when will cialis go generic cialis cost viagra vs cialis levitra dosage how much does cialis cost cialis copay card over the counter viagra does viagra work natural viagra alternatives that work otc viagra cialis trial is viagra federally funded trial viagra sample cilias cialis coupons from manufacturer how long does viagra last viagra pills for sale viagra for sale cialis without a doctor's prescription cialis sample generic cialis cialis samples online cialis what is viagra cialis tadalafil viagra samples viagra costs daily cialis generic viagra levitra canada levitra coupon viagra canada cialis website order online viagra cialis 30 day trial coupon viagra ingredients where to buy viagra viagra from amazon viagra government funding levitra vs viagra for hardness liquid cialis what is levitra free cialis cialis or viagra cialis coupons printable cialis 30 day sample cialis professional viagra dose cialis pricing cost of cialis cialis coupon pfizer viagra viagra dosage viagra single packs viagra activate cialis savings card generic cialis tadalafil viagra porn viagra prices cialis generic tadalafil cost of viagra cialis for women how does viagra work levitra side effects generic for cialis 9 levitra at walmart cialis alternative cialis 5 mg walgreens viagra substitute viagra patent expiration viagra savings offer viagra cialis viagra 100mg tablets retail price female viagra pills viagra coupon cialis otc cialis pills stendra vs viagra viagra without a doctor prescription usa 200 cialis coupon wholesale cialis viagra girls is viagra government funded price cialis cialis generic availability viagra without a doctor prescription cialis prices cialis samples overnight generic viagra available in usa generic for viagra cialas cialis for daily use cialis for sale cialis for bph

Hello World with Node.js

Posted on in JavaScript Node JS

See the example below for an easy Hello World example with Node.js. Create a Node.JS server and serve a hardcoded response, with content-type: ?text/html?. And listen to localhost:8000 in your browser to see the result. In your project folder create an app.js file:

var http = require('http');
http.createServer(function(req, res){ 
   var html = BoilerplateHello World"; 
   res.writeHead(200, { 
      'Content-Type' : 'text/html', 'Content-Length' : html.length 
   }); 
   res.end(html);
}).listen(8000,'127.0.0.1');

With the above example you can?t create a real-life application. Let?s create an MVC folder structure in your project folder. By creating the following folders: ?controller?, ?model?, ?views?. In the ?views? directory, create here an index.html file. With the following content:

Then change your app.js file like the example below to retrieve the index.html file from the views folder:

var http = require('http');
var path = require('path');
var fs = require('fs');
http.createServer(function(req, res){ 
   var filename = path.basename(req.url) || 'index.html', 
   ext = path.extname(filename), 
   localPath = __dirname + "/views/"; 
   //console.log(localPath); 

   if(ext == ".html"){ 
      localPath += filename; 
      path.exists(localPath, function(exists){ 
         if(exists){ 
            getFile(localPath, res) 
         } else { 
            res.writeHead(404); 
            res.end(); 
         } 
       }); 
    }
}).listen(8000, '127.0.0.1'); 
getFile = function(localPath,res){ 
   fs.readFile(localPath, function(err, contents){ 
      if(!err){ 
         res.end(contents); 
      } else { 
         res.writeHead(500); 
         res.end(); 
      } 
});

what is levitra cialis professional cialis coupons printable viagra dose online viagra does the government fund viagra levitra coupon cost of levitra buy viagra generic for viagra cialis coupons from manufacturer what is cialis cialis otc viagra patent expiration discount viagra cialis 20mg buy levitra online viagra 100mg price walmart inexpensive viagra pills levitra vs cialis cost of viagra natural viagra over the counter viagra generic for cialis utilisation viagra where to buy viagra cialis prices cyalis healthy man viagra viagra without a doctor prescription viagra price 9 levitra at walmart levitra canada sildenafil vs viagra how long does levitra last viagra alternatives cialis 5mg daily levitra vs viagra cialis 20 mg viagra vs cialis vs levitra viagra prices without insurance women viagra cialis coupons 2017 cialis vs viagra canadian viagra levitra 20mg cialis without a doctor's prescription levitra reviews cialis coupons viagra pill viagra canada non prescribed viagra viagra best price liquid cialis price cialis viagra from amazon how much does cialis cost cialis sample cialis 10 mg viagra coupons 75 off cialis pricing cialis side effects cialis generic viagra side effects best price viagra cialis patent expiration 2017 cialis or viagra trial viagra sample cealis cialis generic tadalafil cheap cialis generic viagra viagra vs cialis side effects of cialis cialis canada female viagra pills cialis free trial cialis on line viagra on line viagra samples erectile dysfunction cialis cialis website canada viagra sex viagra for women buy cialis online cilias cialis cost sophia viagra how long does viagra last cialis cheap stendra vs viagra cost of cialis free cialis levitra side effects generic cialis at walmart female viagra viagra cost cialis testimonials cialis cialis discount viagra generic cialas levitra 10 mg how to take cialis canadian cialis cialis coupon cialis pills for sale viagra activate buy cialis is viagra government funded in america is viagra covered by insurance viagra for sale levitra vs viagra walgreens viagra substitute levitra prices cvs pharmacy viagra coupons generic cialis is viagra government funded cialis generic availability viagra vs cialis vs levitra viagra from canada cialis daily levitra loc us viagra costs side effects of viagra discount cialis cialis 5mg levitra without a doctor prescription what is viagra viagra on line no prec pfizer viagra levitra coupons cialis dosage free viagra levitra cost viagra single packs levitra generic viagra online levitra 10mg generic cialis tadalafil cialis samples cialis price cialis canadian pharmacy cialis pharmacy prices cialis patent expiration levitra cialis medication is viagra federally funded online cialis how much does viagra cost cheap viagra viagra cialis cialis trial cialis for bph cialis effects viagra pills cialis dosage strengths levitra dosage cialis for sale cialis voucher viagra government funding cialis savings card cialis coupon print viagra porn viagra dosage cialis 20mg directions viagra substitute otc viagra levitra online 200 cialis coupon cialis coupon 20 mg cialis online cialis samples overnight cialis for men cialis copay card cialis alternative does viagra work herbal viagra cialis for daily use buy viagra online levitra vs viagra for hardness cialis for women cialis pills canada cialis how does cialis work viagra sex viagra without a doctor prescription usa cialis reviews generic viagra available in usa cialis or viagra wholesale cialis viagra viagra government funded generic viagra 100mg viagra pharmacy generic levitra cialis tadalafil lowest cialis prices cialis vs viagra revatio vs viagra buy levitra natural viagra alternatives that work viagra pills for sale pfizer viagra coupons cialis from canada viagra for women viagra coupon levitra 20 mg cost walmart viagra without prescription when will cialis go generic cialis patent expiration date extended viagra prices viagra single packs cost cialis 5 mg viagra coupons cialis 30 day sample how does viagra work viagra coupons from pfizer daily cialis viagra ingredients cialis dosage recommendations order online viagra viagra savings offer cialis 30 day trial coupon levitra 20 mg what does viagra do is viagra funded by government viamedic cialis viagra girls viagra vs cialis viagra 100mg tablets retail price

Auto restart node after code changes

Posted on in JavaScript Node JS

When you are sick and tired of restarting your node app in the terminal (CTRL+C) on every code change you make then you can automate this process. Actually it?s really simple. Install Nodemon via the package manager.

$ sudo npm install nodemon -p

When you want to check if it correctly installed and on which version you are running Nodemon:

$ nodemon -v
0.6.14

Is everything correctly set? You can start Nodemon, by typing the following command in the root of your current node project. For example:

$ nodemon app.js
9 Apr 20:15:23 - [nodemon] watching: /Users/lee/Projects/nodejs/www
9 Apr 20:15:23 - [nodemon] starting 'node app.js'

is viagra covered by insurance otc viagra levitra coupons cialis savings card levitra prices viagra for women viagra dosage viagra best price viagra substitute levitra 20 mg cialis coupons viagra single packs cost viagra pharmacy viagra online cialis side effects cialis otc non prescribed viagra generic viagra female viagra pills pfizer viagra coupons viagra for sale cost of levitra cialis coupon print cialis coupons printable cialis trial order online viagra viagra activate cialis patent expiration date extended buy cialis online cialis generic availability levitra loc us does the government fund viagra cialis or viagra free cialis discount viagra cialis generic cialis canada viagra on line is viagra government funded levitra dosage levitra vs viagra levitra 20mg viagra cost cheap cialis viagra without prescription how long does viagra last liquid cialis levitra 20 mg cost walmart buy levitra cialis cheap cialis alternative viagra pill viagra porn viagra price what is cialis herbal viagra is viagra government funded in america viagra prices cialis 30 day sample viagra savings offer revatio vs viagra viagra 100mg price walmart levitra viagra 100mg tablets retail price female viagra cialis sample viagra generic viagra vs cialis wholesale cialis viagra alternatives cialis samples cialis 20 mg viagra single packs cialis patent expiration 2017 viagra government funded levitra side effects cialis pills viagra from amazon how much does cialis cost cilias free viagra viagra coupons from pfizer cialas levitra generic how long does levitra last viagra dose cialis pricing levitra cost cialis 10 mg cealis stendra vs viagra side effects of cialis discount cialis viagra coupons viagra prices without insurance levitra online cialis dosage recommendations is viagra funded by government canadian cialis how to take cialis viagra pills viagra girls generic cialis at walmart viagra without a doctor prescription generic for viagra viagra vs cialis cialis 5mg daily cialis effects levitra vs viagra 200 cialis coupon generic cialis tadalafil how much does viagra cost cialis free trial cyalis cialis samples overnight cialis pills for sale generic viagra 100mg cialis price cialis copay card cialis for sale cialis coupon cialis pharmacy prices pfizer viagra cialis 5 mg generic viagra available in usa cialis for bph online viagra cialis online canada cialis utilisation viagra cialis professional cialis canadian pharmacy levitra vs viagra for hardness viagra on line no prec cialis vs viagra cialis tadalafil cialis for women viagra from canada cialis daily cialis without a doctor's prescription cvs pharmacy viagra coupons trial viagra sample cialis reviews cialis vs viagra generic cialis buy levitra online cialis dosage strengths healthy man viagra daily cialis canadian viagra cialis cost cialis for daily use viagra ingredients levitra coupon cialis canada viagra viagra coupons 75 off side effects of viagra sex viagra for women cialis discount levitra 10mg sildenafil vs viagra cialis from canada walgreens viagra substitute levitra 10 mg cialis 5mg viagra viagra patent expiration buy viagra cialis dosage cost of viagra cialis or viagra where to buy viagra cialis coupons from manufacturer 9 levitra at walmart viagra costs cialis 20mg directions natural viagra natural viagra alternatives that work price cialis buy viagra online cialis for men viagra vs cialis vs levitra online cialis viagra without a doctor prescription usa cialis generic tadalafil erectile dysfunction cialis cialis patent expiration levitra canada cialis website how does viagra work when will cialis go generic levitra without a doctor prescription does viagra work what is viagra cialis voucher cialis prices viagra samples cialis testimonials lowest cialis prices generic levitra cialis coupons 2017 cost of cialis cheap viagra viagra cialis viagra government funding sophia viagra cialis on line best price viagra inexpensive viagra pills viagra coupon cialis 30 day trial coupon what does viagra do what is levitra levitra reviews women viagra viagra sex viamedic cialis generic for cialis buy cialis cialis medication cialis coupon 20 mg is viagra federally funded viagra vs cialis vs levitra viagra pills for sale how does cialis work viagra side effects cialis 20mg over the counter viagra levitra vs cialis viagra canada