Tuesday, May 9, 2017

What does npm start do in nodejs

When you issue the com­mand npm start from the root direc­tory of your nodejs project, node will look for a scripts object in your package.json file. If found, it will look for a script with the key start and run the com­mand spec­i­fied as its value.
If your package.json does not have any scripts object or if the scripts object does not have a start key, it will run the com­mand node server.js instead.
Npm scripts are pretty use­ful because they let you group together and run log­i­cally related com­mands. e.g. lin­ters, mini­fiers etc.

Tuesday, May 2, 2017

Starting with Java and Node.js development on Ubuntu Linux

2015-07-09 00:00:00 +0000
by Paul Verest
Ubuntu is major Linux distribution (wikipedia article)
One should select LTS version, as for example Help is full only for LTS versions and Node.js packages are supported for LTS but not latest versions.

Installing Java JDK 8

There are many Java implementations for Ubuntu. Let's stick with Oracle JDK:
http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
Check what exact version you got:
java -version
javac -version  
See also https://www.digitalocean.com/community/tutorials/how-to-install-java-on-ubuntu-with-apt-get

Install Enide 2015 (Eclipse-based IDE)

Based on http://ubuntuhandbook.org/index.php/2014/06/install-latest-eclipse-ubuntu-14-04/
  1. Download Enide for Linux, e.g. Enide-2015-7.
  2. Extract to e.g. /opt/Eclipses/Enide-2015-7-linux-gtk-x64-20150706/
    sudo nautilus ~/Downloads sudo nautilus /opt
  3. Allow eclipse to be executable. From the /opt/Eclipses/Enide-2015-7-linux-gtk-x64-20150706/eclipse/ folder
    sudo chmod -R 7555 eclipse
  4. Create shortcut
    sudo gedit /usr/share/applications/enide-2015-7.desktop
paste
[Desktop Entry]
Name=Enide-2015-7
Type=Application
Exec=/opt/Eclipses/Enide-2015-7-linux-gtk-x64-20150706/eclipse/eclipse
Terminal=false
Icon=/opt/Eclipses/Enide-2015-7-linux-gtk-x64-20150706/eclipse/icon.xpm
Comment=Enide 2015-7 (Eclipse 4.5 Mars-based)
NoDisplay=false
Categories=Development;IDE;
Name[en]=Enide-2015-7
See also http://askubuntu.com/questions/337281/installing-eclipse-kepler

Installing Node.js

https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager
https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-an-ubuntu-14-04-server
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
Or the latest using https://github.com/nodesource/distributions
curl -sL https://deb.nodesource.com/setup_0.12 | sudo -E bash -
sudo apt-get install -y nodejs  
comments powered by Disqus

Top 10 IDEs for Developing Node.js Apps

Having control over code is an important part of a software application development process. A lot of programmers need efficient code editing and debugging tools to work with accuracy and speed. This may be the reason as to why an IDE (Integrated development environment) was conceptualized. An IDE has a source code editor, a code debugger, code completion feature, build automation tool, compiler and more all in one single software application. Modern IDEs have a graphical user interface with a single program which offers several features, such as authoring, compiling, deploying and debugging software code.

Some IDEs are dedicated to a specific, single programming language while there are a few more that support multiple languages. Eclipse, NetBeans, CodeEnvy, Xojo and Xcode are some examples of modern IDEs.

Here, we are focusing only upon IDEs for Node.js applications. We are aware that Node.js has successfully captured the mainstream technology market with large-scale companies like IBM, Yahoo!, Walmart, SAP and others using it. These days, Node.js application development is gaining momentum and it is used by a vast community of developers, technology enthusiasts and programmers.

Node.js is an open-source, runtime environment for developing server-side and network applications in JavaScript. Its event-driven architecture and non-blocking I/O model makes it ideal for building real-time applications that run across distributed devices.

In our last post of Node.js I have highlighted some of best web hosting platforms for Node.js applicaition, today I have listed down the names of major IDEs for Node.js development. Most of them support multiple platforms like OSX, LINUX and Windows. I have also listed down some names of popular text editors since they perform much of the required job.

Alright, so check out this list of Top 10 IDEs for developing node.js applications.

1) Cloud 9

Cloud 9
Cloud 9 is a free, cloud-based IDE supporting application development with popular technologies, including Node.js, PHP, C++, Meteor and more. It offers a powerful online code editor that lets you write, run and debug your code. Moreover, Cloud 9 provides several features, such as key binding editor, built-in image editor, live previewing and a lot more.
Also See: 5 Free Beginner Friendly Books for Learning Node.js

2) Intellij IDEA

Intellij IDEA
Intellij IDEA is a robust IDE for web application development using popular technologies, such as Node.js, Angular.js, JavaScript, HTML5 and more. You need a Node.js plugin to enable the IDE and use features, including syntax highlighting, code assistance, code completion and more. You can run and debug Node.js apps and see the results right in the IDE. Its JavaScript debugger offers conditional breakpoints, expression evaluation and other features.

3) WebStorm

WebStorm
WebStorm is a popular JavaScript IDE, which is ideal for server-side development with Node.js. The IDE provides intelligent code completion, navigation, automated and safe refactorings and other features. Additionally, you can use the debugger, VCS, terminal and other tools right in the IDE.
Also Check: How Node.js is changing the way we use JavaScript

4) Komodo IDE

Komodo
Komodo is a cross-platform IDE supporting major programming languages, including Node.js, Ruby, PHP, JavaScript and more. The IDE allows you to run commands, create custom configurations, track changes and use shortcuts. It also provides syntax/highlighting, code intelligence, language icons, multiple selections, markdown viewer, DOM viewer, graphical debugging and more.

5) Koding

Koding
Koding is an open-source, cloud-based IDE for developing applications using Node.js, PHP, Ruby and more. The IDE offers a variety of features, including syntax highlighting, keyboard shortcuts, collapsible panes, workspace, auto indenting, code folding and code preview using built-in browser. Koding offers multi-cursor support to allow making similar edits at once.

6) Eclipse

Eclipse
Eclipse is a popular cloud-based IDE for web development using Java, PHP, C++ and more. You can easily avail the features of Eclipse IDE using the Node.js plugin, which is nodeclipse.
Also Read: 10 Best IDEs For Linux

7) WebMatrix

WebMatrix
WebMatrix is a free and cloud-based IDE for Windows platform. It supports web development using Node.js with features, such as code completion, built-in templates and publishing to the cloud. WebMatrix has built-in Node.js templates for website and web application development that use Express, routing, OAuth, and more.

8) Sublime Text

Sublime Text
Sublime Text uses a custom UI toolkit with a powerful text editor for code, markup and prose. You can jump to symbols, lines or words using shortcuts and use multiple selection option to rename variables and manipulate files faster. Sublime Text also offers options for split editing, customizing, project switching and more.

9) Atom

Atom
Atom is a text editor with modern code completion features. It comes pre-installed with four UI and eight syntax themes and is easily customizable. Atom is an open-source application, which is built with HTML, JavaScript, CSS and Node.js integration. It runs on the Electron framework for building cross-platform apps using popular web technologies.
Also See: 10 Best Java Ides For Java Programmers

10) Brackets

Brackets
Brackets is a text editor offering advanced features, such as inline editing, live code previewing, preprocessor support, code folding and command line integration. Brackets is an open-source project started by Adobe systems. Extract for Brackets is an adobe extension that lets you pull design information from PSD files, such as colors, fonts, gradients and measurement information and turn it in to CSS.

Conclusion:
If you are a Node.js developer, then there is no lack of necessary tools to get your job done. There are a lot of testing tools, frameworks and IDEs available for Node.js application development. A lot of application developers are currently working to develop an array of useful applications using Node.js framework. One can easily develop real-time web applications, such as instant messaging or chat applications using Node.js. KeystoneJS is an example of a content management system (CMS) built using Node.js. It is used for building database-driven, modern websites as well as applications and application programming interfaces (APIs). Another is Ghost, a popular blogging platform. Moreover, you can also build servers, games, websites, content management systems and a lot more using this powerful technology.

I am sure you must have found this list helpful and will definitely find the perfect Node.js IDE from this list.  You can share your feedback on this topic by writing your comments in the comments section below. Good Luck!!!

Monday, May 1, 2017

heroku: Deploying with Git

Git is a powerful decentralized revision control system, and is the means for deploying apps to Heroku. You don’t need to be proficient with Git to use it for deploying code to Heroku, but you may find it valuable to learn the basics.

Tracking your app in git

Heroku apps expect the app directory structure at the root of the repository. If your app is inside a subdirectory in your repository, it won’t run when pushed to Heroku.
Before you can push an app to Heroku, you’ll need to initialize a local Git repository and commit your files to it. For example, if you have an app in a directory, myapp, then create a new repository for it:
 cd myapp
 git init
Initialized empty Git repository in .git/
 git add .
 git commit -m "my first commit"
Created initial commit 5df2d09: my first commit
 44 files changed, 8393 insertions(+), 0 deletions(-)
 create mode 100644 README
 create mode 100644 Procfile
 create mode 100644 app/controllers/source_file
...
This is a local repository, now residing inside the .git directory. Nothing has been sent anywhere yet; you’ll need to create a remote and do a push to deploy your code to Heroku.

Creating a Heroku remote

Git remotes are references to remote repositories. You can have any number of these, but for now we’ll focus on just the remote to Heroku. The heroku create command creates a new application on Heroku – along with a git remote that must be used to receive your application source.
 heroku create
Creating falling-wind-1624... done, stack is cedar-14
http://falling-wind-1624.herokuapp.com/ | https://git.heroku.com/falling-wind-1624.git
Git remote heroku added
By default, Heroku configures HTTP as the Git transport. The Heroku CLI will automatically place credentials in the .netrc file on heroku login. The Git client uses cURL when interacting with HTTP remotes, and cURL will use the credentials from the .netrc file. See the Authentication section and the CLI authentication article for details.
You can verify the remote in your git configuration as well:
 git remote -v
heroku  https://git.heroku.com/falling-wind-1624.git (fetch)
heroku  https://git.heroku.com/falling-wind-1624.git (push)
You can also take an existing Git repository and add a remote using the git URL provided when you created your app. You may need to do this to associate a Git repository with an existing application. The heroku git:remote command will add this remote for you based on your applications git url.
 heroku git:remote -a falling-wind-1624
Git remote heroku added.
The remote is named heroku in this example, but you can name the remote anything you want by passing -r other_remote_name. You may find it easier to follow the examples if you stick to using the heroku remote rather than using one with a different name.
There is one special remote name: origin, which is the default for pushes. Using origin as the remote name will allow you to type just git push instead of git push heroku, but we recommend using an explicitly named remote.
To switch from SSH Git to HTTP Git, run heroku git:remote in the directory holding your local Git repository. The CLI will override the heroku Git remote to use the HTTP protocol.

Deploying code

Your Heroku app starts with a blank repository – it has no branches and no code. So the first time you deploy, you’ll need to specify a remote branch to push to. You can do your first push:
 git push heroku master
Initializing repository, done.
updating 'refs/heads/master'
...
This will push your code to the heroku remote, created earlier. Use this whenever you want to deploy the latest code committed in Git to Heroku.
During the start of your first build, Initializing repository will be displayed while your app’s repository is created on Heroku. On subsequent builds, Fetching repository will be displayed while your app’s repository is fetched and prepared to accept your push.
Branches pushed to Heroku other than master will be ignored by this command. If you’re working out of another branch locally, you can either merge to master before pushing, or specify that you want to push your local branch to a remote master. To push a branch other than master, use this syntax:
 git push heroku yourbranch:master
Applications that rely on git submodules are supported, in addition to many other dependency resolution strategies.

How Heroku Works (the only free nodejs hosting domain untill now)

This is a high-level, technical description of how Heroku works. It ties together many of the concepts you’ll encounter while writing, configuring, deploying and running applications on the Heroku platform.
Performing one of the Getting Started tutorials will make the concepts in this documentation more concrete.
Read this document sequentially: in order to tell a coherent story, it incrementally unveils and refines the concepts describing the platform.
The final section ties all the definitions together, providing a deploy-time and runtime-view of Heroku.

Defining an application

Heroku lets you deploy, run and manage applications written in Ruby, Node.js, Java, Python, Clojure, Scala, Go and PHP.
An application is a collection of source code written in one of these languages, perhaps a framework, and some dependency description that instructs a build system as to which additional dependencies are needed in order to build and run the application.
Terminology (Preliminary): Applications consist of your source code and a description of any dependencies.
Dependency mechanisms vary across languages: in Ruby you use a Gemfile, in Python a requirements.txt, in Node.js a package.json, in Java a pom.xml and so on.
The source code for your application, together with the dependency file, should provide enough information for the Heroku platform to build your application, to produce something that can be executed.

Knowing what to execute

You don’t need to make many changes to an application in order to run it on Heroku. One requirement is informing the platform as to which parts of your application are runnable.
If you’re using some established framework, Heroku can figure it out. For example, in Ruby on Rails, it’s typically rails server, in Django it’s python <app>/manage.py runserver and in Node.js it’s the main field in package.json.
Terminology: Procfiles list process types - named commands that you may want executed.
For other applications, you may need to explicitly declare what can be executed. You do this in a text file that accompanies your source code - a Procfile. Each line declares a process type - a named command that can be executed against your built application. For example, your Procfile may look like this:
web: java -jar lib/foobar.jar $PORT
queue: java -jar lib/queue-processor.jar
This file declares a web process type and provides the command that needs to be executed in order to run it (in this case, java -jar lib/foobar.jar $PORT). It also declares a queue process type, and its corresponding command.
The earlier definition of an application can now be refined to include this single additional Procfile.
Terminology: Applications consist of your source code, a description of any dependencies, and a Procfile.
Heroku is a polyglot platform – it lets you build, run and scale applications in a similar manner across all the languages – utilizing the dependencies and Procfile. The Procfile exposes an architectural aspect of your application (in the above example there are two entry points to the application) and this architecture lets you, for example, scale each part independently. An excellent guide to architecture principles that work well for applications running on Heroku can be found in Architecting Applications for Heroku.

Deploying applications

Git is a powerful, distributed version control system that many developers use to manage and version source code. The Heroku platform uses git as the primary means for deploying applications (there are other ways to transport your source code to Heroku, including via an API).
When you create an application on Heroku, it associates a new git remote, typically named heroku, with the local git repository for your application.
As a result, deploying code is just the familiar git push, but to the heroku remote instead:
 git push heroku master
Terminology: Deploying applications involves sending the application to Heroku using either git, GitHub, Dropbox, or via an API.
There are many other ways of deploying applications too. For example, you can enable GitHub integration so that each new pull request is associated with its own new application, which enables all sorts of continuous integration scenarios. Or you can use Dropbox Sync, which lets you deploy the contents of Dropbox folders to Heroku. Finally, you can also use the Heroku API to build and release apps.
Deployment then, is about moving your application from your local system to Heroku - and Heroku provides several ways in which apps can be deployed.

Building applications

When the Heroku platform receives the application source, it initiates a build of the source application. The build mechanism is typically language specific, but follows the same pattern, typically retrieving the specified dependencies, and creating any necessary assets (whether as simple as processing style sheets or as complex as compiling code).
Advanced: Buildpacks lie behind the slug compilation process. Buildpacks take your application, its dependencies, and the language runtime, and produce slugs. They’re open source - enabling you to extend Heroku to other languages and frameworks.
For example, when the build system receives a Rails application, it may fetch all the dependencies specified in the Gemfile, as well as generate files based on the asset pipeline. A Java application may fetch binary library dependencies using Maven, compile the source code together with those libraries, and produce a JAR file to execute.
The source code for your application, together with the fetched dependencies and output of the build phase such as generated assets or compiled code, as well as the language and framework, are assembled into a slug.
Terminology: A slug is a bundle of your source, fetched dependencies, the language runtime, and compiled/generated output of the build system - ready for execution.
These slugs are a fundamental aspect of what happens during application execution - they contain your compiled, assembled application - ready to run - together with the instructions (the Procfile) of what you may want to execute.

Running applications on dynos

Heroku executes applications by running a command you specified in the Procfile, on a dyno that’s been preloaded with your prepared slug (in fact, with your release, which extends your slug and a few items not yet defined: config vars and add-ons).
Think of a running dyno as a lightweight, secure, virtualized Unix container that contains your application slug in its file system.
Terminology: Dynos are isolated, virtualized Unix containers, that provide the environment required to run an application.
Generally, if you deploy an application for the first time, Heroku will run 1 web dyno automatically. In other words, it will boot a dyno, load it with your slug, and execute the command you’ve associated with the web process type in your Procfile.
You have control over how many dynos are running at any given time. Given the Procfile example earlier, you can start 5 dynos, 3 for the web and 2 for the queue process types, as follows:
 heroku ps:scale web=3 queue=2
When you deploy a new version of an application, all of the currently executing dynos are killed, and new ones (with the new release) are started to replace them - preserving the existing dyno formation.
Terminology: Your application’s dyno formation is the total number of currently-executing dynos, divided between the various process types you have scaled.
To understand what’s executing, you just need to know what dynos are running which process types:
 heroku ps
== web: 'java lib/foobar.jar $PORT'
web.1: up 2013/02/07 18:59:17 (~ 13m ago)
web.1: up 2013/02/07 18:52:08 (~ 20m ago)
web.2: up 2013/02/07 18:31:14 (~ 41m ago)

== queue: `java lib/queue-processor.jar`
queue.1: up 2013/02/07 18:40:48 (~ 32m ago)
queue.2: up 2013/02/07 18:40:48 (~ 32m ago)
Dynos then, are an important means of scaling your application. In this example, the application is well architected to allow for the independent scaling of web and queue worker dynos.

Config vars

An application’s configuration is everything that is likely to vary between environments (staging, production, developer environments, etc.). This includes backing services such as databases, credentials, or environment variables that provide some specific information to your application.
Heroku lets you run your application with a customizable configuration - the configuration sits outside of your application code and can be changed independently of it.
The configuration for an application is stored in config vars. For example, here’s how to configure an encryption key for an application:
 heroku config:set ENCRYPTION_KEY=my_secret_launch_codes
Adding config vars and restarting demoapp... done, v14
ENCRYPTION_KEY:     my_secret_launch_codes
Terminology: Config vars contain customizable configuration data that can be changed independently of your source code. The configuration is exposed to a running application via environment variables.
At runtime, all of the config vars are exposed as environment variables - so they can be easily extracted programatically. A Ruby application deployed with the above config var can access it by calling ENV["ENCRYPTION_KEY"].
All dynos in an application will have access to the exact same set of config vars at runtime.

Releases

Earlier, this article stated that to run your application on a dyno, the Heroku platform loaded the dyno with your most recent slug. This needs to be refined: in fact it loads it with the slug and any config variables you have assigned to the application. The combination of slug and configuration is called a release.
Terminology (Preliminary): Releases are an append-only ledger of slugs and config vars.
All releases are automatically persisted in an append-only ledger, making managing your application, and different releases, a cinch. Use the heroku releases command to see the audit trail of release deploys:
 heroku releases
== demoapp Releases
v103 Deploy 582fc95  jon@heroku.com   2013/01/31 12:15:35
v102 Deploy 990d916  jon@heroku.com   2013/01/31 12:01:12
The number next to the deploy message, for example 582fc95, corresponds to the commit hash of the repository you deployed to Heroku.
Every time you deploy a new version of an application, a new slug is created and release is generated.
As Heroku contains a store of the previous releases of your application, it’s very easy to rollback and deploy a previous release:
 heroku releases:rollback v102
Rolling back demoapp... done, v102
 heroku releases
== demoapp Releases
v104 Rollback to v102 jon@heroku.com   2013/01/31 14:11:33 (~15s ago)
v103 Deploy 582fc95   jon@heroku.com   2013/01/31 12:15:35
v102 Deploy 990d916   jon@heroku.com   2013/01/31 12:01:12
Making a material change to your application, whether it’s changing the source or configuration, results in a new release being created.
A release then, is the mechanism behind how Heroku lets you modify the configuration of your application (the config vars) independently of the application source (stored in the slug) - the release binds them together. Whenever you change a set of config vars associated with your application, a new release will be generated.

Dyno manager

Part of the Heroku platform, the dyno manager, is responsible for keeping dynos running. For example, dynos are cycled at least once per day, or whenever the dyno manager detects a fault in the running application (such as out of memory exceptions) or problems with the underlying hardware that requires the dyno be moved to a new physical location.
Terminology: The dyno manager of the Heroku platform is responsible for managing dynos across all applications running on Heroku.
This dyno cycling happens transparently and automatically on a regular basis, and is logged.
Terminology: Applications that use the free dyno type will sleep. When a sleeping application receives HTTP traffic, it will be awakened - causing a delay of a few seconds. Using one of the other dyno types will avoid sleeping.
Because Heroku manages and runs applications, there’s no need to manage operating systems or other internal system configuration. One-off dynos can be run with their input/output attached to your local terminal. These can also be used to carry out admin tasks that modify the state of shared resources, for example database configuration - perhaps periodically through a scheduler.
Terminology: One-off Dynos are temporary dynos that can run with their input/output attached to your local terminal. They’re loaded with your latest release.
Here’s the simplest way to create and attach to a one-off dyno:
 heroku run bash
Running `bash` attached to terminal... up, run.8963
~ $ ls
This will spin up a new dyno, loaded with your release, and then run the bash command - which will provide you with a unix shell (remember that dynos are effectively isolated virtualized unix containers). Once you’ve terminated your session, or after a period of inactivity, the dyno will be removed.
Changes to the filesystem on one dyno are not propagated to other dynos and are not persisted across deploys and dyno restarts. A better and more scalable approach is to use a shared resource such as a database or queue.
Terminology: Each dyno gets its own ephemeral filesystem - with a fresh copy of the most recent release. It can be used as temporary scratchpad, but changes to the filesystem are not reflected to other dynos.
The ephemeral nature of the file system in a dyno can be demonstrated with the above command. If you create a one-off dyno by running heroku run bash, the Unix shell on the dyno, and then create a file on that dyno, and then terminate your session - the change is lost. All dynos, even those in the same application, are isolated - and after the session is terminated the dyno will be killed. New dynos are always created from a slug, not from the state of other dynos.

Add-ons

Applications typically make use of add-ons to provide backing services such as databases, queueing & caching systems, storage, email services and more. Add-ons are provided as services by Heroku and third parties - there’s a large marketplace of add-ons you can choose from.
Heroku treats these add-ons as attached resources: provisioning an add-on is a matter of choosing one from the add-on marketplace, and attaching it to your application.
For example, here is how to add the Heroku Redis backing store add-on to an application:
 heroku addons:create heroku-redis:hobby-dev
Dynos do not share file state, and so add-ons that provide some kind of storage are typically used as a means of communication between dynos in an application. For example, Redis or Postgres could be used as the backing mechanism in a queue; then dynos of the web process type can push job requests onto the queue, and dynos of the queue process type can pull jobs requests from the queue.
The add-on service provider is responsible for the service - and the interface to your application is often provided through a config var. In this example, a REDIS_URL will be automatically added to your application when you provision the add-on. You can write code that connects to the service through the URL, for example:
uri = URI.parse(ENV["REDIS_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
Terminology: Add-ons are third party, specialized, value-added cloud services that can be easily attached to an application, extending its functionality.
Add-ons are associated with an application, much like config vars - and so the earlier definition of a release needs to be refined. A release of your applications is not just your slug and config vars; it’s your slug, config vars as well as the set of provisioned add-ons.
Terminology: Releases are an append-only ledger of slugs, config vars and add-ons. Heroku maintains an append-only ledger of releases you make.
Much like config vars, whenever you add, remove or change an add-on, a new release is created.

Logging and monitoring

Heroku treats logs as streams of time-stamped events, and collates the stream of logs produced from all of the processes running in all dynos, and the Heroku platform components, into the Logplex - a high-performance, real-time system for log delivery.
It’s easy to examine the logs across all the platform components and dynos:
 heroku logs
2013-02-11T15:19:10+00:00 heroku[router]: at=info method=GET path=/articles/custom-domains host=mydemoapp.heroku.com fwd=74.58.173.188 dyno=web.1 queue=0 wait=0ms connect=0ms service=1452ms status=200 bytes=5783
2013-02-11T15:19:10+00:00 app[web.2]: Started GET "/" for 1.169.38.175 at 2013-02-11 15:19:10 +0000
2013-02-11T15:19:10+00:00 app[web.1]: Started GET "/" for 2.161.132.15 at 2013-02-11 15:20:10 +0000
Here you see 3 timestamped log entries, the first from Heroku’s router, the last two from two dynos running the web process type.
Terminology: Logplex automatically collates log entries from all the running dynos of your app, as well as other components such as the routers, providing a single source of activity.
You can also dive into the logs from just a single dyno, and keep the channel open, listening for further events:
 heroku logs --ps web.1 --tail
2013-02-11T15:19:10+00:00 app[web.2]: Started GET "/" for 1.169.38.175 at 2013-02-11 15:19:10 +0000
Logplex keeps a limited buffer of log entries solely for performance reasons. To persist them, and action events such as email notification on exception, use a Logging Add-on, which ties into log drains - an API for receiving the output from Logplex.

HTTP routing

Depending on your dyno formation, some of your dynos will be running the command associated with the web process type, and some will be running other commands associated with other process types.
The dynos that run process types named web are different in one way from all other dynos - they will receive HTTP traffic. Heroku’s HTTP routers distribute incoming requests for your application across your running web dynos.
So scaling an app’s capacity to handle web traffic involves scaling the number of web dynos:
 heroku ps:scale web+5
A random selection algorithm is used for HTTP request load balancing across web dynos - and this routing handles both HTTP and HTTPS traffic. It also supports multiple simultaneous connections, as well as timeout handling.

Tying it all together

The concepts explained here can be divided into two buckets: those that involve the development and deployment of an application, and those that involve the runtime operation of the Heroku platform and the application after it’s deployed.
The following two sections recapitulate the main components of the platform, separating them into these two buckets.

Deploy

  • Applications consist of your source code, a description of any dependencies, and a Procfile.
  • Procfiles list process types - named commands that you may want executed.
  • Deploying applications involves sending the application to Heroku using either git, GitHub, Dropbox, or via an API.
  • Buildpacks lie behind the slug compilation process. Buildpacks take your application, its dependencies, and the language runtime, and produce slugs.
  • A slug is a bundle of your source, fetched dependencies, the language runtime, and compiled/generated output of the build system - ready for execution.
  • Config vars contain customizable configuration data that can be changed independently of your source code. The configuration is exposed to a running application via environment variables.
  • Add-ons are third party, specialized, value-added cloud services that can be easily attached to an application, extending its functionality.
  • A release is a combination of a slug (your application), config vars and add-ons. Heroku maintains an append-only ledger of releases you make.

Runtime

  • Dynos are isolated, virtualized unix containers, that provide the environment required to run an application.
  • Your application’s dyno formation is the total number of currently-executing dynos, divided between the various process types you have scaled.
  • The dyno manager is responsible for managing dynos across all applications running on Heroku.
  • Applications that use the free dyno type will sleep after 30 minutes of inactivity. Scaling to multiple web dynos, or a different dyno type, will avoid this.
  • One-off Dynos are temporary dynos that run with their input/output attached to your local terminal. They’re loaded with your latest release.
  • Each dyno gets its own ephemeral filesystem - with a fresh copy of the most recent release. It can be used as temporary scratchpad, but changes to the filesystem are not reflected to other dynos.
  • Logplex automatically collates log entries from all the running dynos of your app, as well as other components such as the routers, providing a single source of activity.
  • Scaling an application involves varying the number of dynos of each process type.

Next steps

helloworld

An example of a web server written with Node.js which responds with 'Hello World':
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
To run the server, put the code into a file called example.js and execute it with Node.js:
$ node example.js
Server running at http://127.0.0.1:3000/

Tutorial: using a NodeJS hosting - heroku

Set up

In this step you will install the Heroku Command Line Interface (CLI), formerly known as the Heroku Toolbelt. You will use the CLI to manage and scale your applications, to provision add-ons, to view the logs of your application as it runs on Heroku, as well as to help run your application locally.
Download the Heroku CLI for...
Once installed, you can use the heroku command from your command shell.
Log in using the email address and password you used when creating your Heroku account:
 heroku login
Enter your Heroku credentials.
Email: zeke@example.com
Password:
...
Authenticating is required to allow both the heroku and git commands to operate.
If you’re behind a firewall that requires use of a proxy to connect with external HTTP/HTTPS services, you can set the HTTP_PROXY or HTTPS_PROXY environment variables in your local development environment before running the heroku command.
Before you continue, check that you have the prerequisites installed properly. Type each command below and make sure it displays the version you have installed. (Your versions might be different from the example.) If no version is returned, go back to the introduction of this tutorial and install the prerequisites.
All of the following local setup will be required to complete the “Declare app dependencies” and subsequent steps.
This tutorial will work for any version of Node greater than 4 or so - check that it’s there:
 node -v
v5.9.1
npm is installed with Node, so check that it’s there. If you don’t have it, install a more recent version of Node:
 npm -v
3.7.3
Now check that you have git installed. If not, install it and test again.
 git --version
git version 2.2.1

 

Prepare the app

In this step, you will prepare a simple application that can be deployed.
To clone the sample application so that you have a local version of the code that you can then deploy to Heroku, execute the following commands in your local command shell or terminal:
 git clone https://github.com/heroku/node-js-getting-started.git
 cd node-js-getting-started
You now have a functioning git repository that contains a simple application as well as a package.json file, which is used by Node’s dependency manager.

Deploy the app

In this step you will deploy the app to Heroku.
Create an app on Heroku, which prepares Heroku to receive your source code.
 heroku create
Creating sharp-rain-871... done, stack is cedar-14
http://sharp-rain-871.herokuapp.com/ | https://git.heroku.com/sharp-rain-871.git
Git remote heroku added
When you create an app, a git remote (called heroku) is also created and associated with your local git repository.
Heroku generates a random name (in this case sharp-rain-871) for your app, or you can pass a parameter to specify your own app name.
Now deploy your code:
 git push heroku master
Counting objects: 343, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (224/224), done.
Writing objects: 100% (250/250), 238.01 KiB, done.
Total 250 (delta 63), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NPM_CONFIG_PRODUCTION=true
remote:        NODE_MODULES_CACHE=true
remote:
remote: -----> Installing binaries
remote:        engines.node (package.json):  5.9.1
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Downloading and installing node 5.9.1...
remote:        Using default npm version: 2.7.4
       ....
remote: -----> Build succeeded!
remote:        ├── ejs@2.4.1
remote:        └── express@4.13.3
remote:
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing... done, 9.4MB
remote: -----> Launching... done, v8
remote:        http://sharp-rain-871.herokuapp.com deployed to Heroku
To https://git.heroku.com/nameless-savannah-4829.git
 * [new branch]      master -> master
The application is now deployed. Ensure that at least one instance of the app is running:
 heroku ps:scale web=1
Now visit the app at the URL generated by its app name. As a handy shortcut, you can open the website as follows:
 heroku open 

Scale the app

Right now, your app is running on a single web dyno. Think of a dyno as a lightweight container that runs the command specified in the Procfile.
You can check how many dynos are running using the ps command:
 heroku ps
=== web (Free): `node index.js`
web.1: up 2014/04/25 16:26:38 (~ 1s ago)
By default, your app is deployed on a free dyno. Free dynos will sleep after a half hour of inactivity (if they don’t receive any traffic). This causes a delay of a few seconds for the first request upon waking. Subsequent requests will perform normally. Free dynos also consume from a monthly, account-level quota of free dyno hours - as long as the quota is not exhausted, all free apps can continue to run.
To avoid dyno sleeping, you can upgrade to a hobby or professional dyno type as described in the Dyno Types article. For example, if you migrate your app to a professional dyno, you can easily scale it by running a command telling Heroku to execute a specific number of dynos, each running your web process type.
Scaling an application on Heroku is equivalent to changing the number of dynos that are running. Scale the number of web dynos to zero:
 heroku ps:scale web=0
Access the app again by hitting refresh on the web tab, or heroku open to open it in a web tab. You will get an error message because you no longer have any web dynos available to serve requests.
Scale it up again:
 heroku ps:scale web=1
For abuse prevention, scaling a non-free application to more than one dyno requires account verification.

Run the app locally

Now start your application locally using the heroku local command, which was installed as part of the Heroku CLI:
 heroku local web
[OKAY] Loaded ENV .env File as KEY=VALUE Format
1:23:15 PM web.1 |  Node app is running on port 5000
Just like Heroku, heroku local examines the Procfile to determine what to run.
Open http://localhost:5000 with your web browser. You should see your app running locally.
To stop the app from running locally, in the CLI, press Ctrl+C to exit.

Push local changes

In this step you’ll learn how to propagate a local change to the application through to Heroku. As an example, you’ll modify the application to add an additional dependency and the code to use it.
Begin by adding a dependency for cool-ascii-faces in package.json. Run the following command to do this:
 npm install --save --save-exact cool-ascii-faces
cool-ascii-faces@1.3.3 node_modules/cool-ascii-faces
└── stream-spigot@3.0.5 (xtend@4.0.1, readable-stream@1.1.13)
Modify index.js so that it requires this module at the start. Also add a new route (/cool) that uses it. Your final code should look like this:
var cool = require('cool-ascii-faces');
var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index')
});

app.get('/cool', function(request, response) {
  response.send(cool());
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Now test locally:
 npm install
 heroku local
Visiting your application at http://localhost:5000/cool, you should see cute faces displayed on each refresh: ( ⚆ _ ⚆ ).
Now deploy. Almost every deploy to Heroku follows this same pattern. First, add the modified files to the local git repository:
 git add .
Now commit the changes to the repository:
 git commit -m "Demo"
Now deploy, just as you did previously:
 git push heroku master
Finally, check that everything is working:
 heroku open cool
You should see another face.


 

Node.js Get Started w3schools

Download Node.js

The official Node.js website has installation instructions for Node.js: https://nodejs.org

Getting Started

Once you have downloaded and installed Node.js on your computer, lets try to display "Hello World" in a web browser.
Create a Node.js file named "myfirst.js", and add the following code:
myfirst.js
var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');
}).listen(8080);
Save the file on your computer: C:\User\Your Name\myfirst.js
The code tells the computer to write "Hello World!" if anyone (e.g. a web browser) tries to access your computer on port 8080.
For now, you do not have to understand the code. It will be explained later.

Command Line Interface

Node.js files must be initiated in the "Command Line Interface" program of your computer.
How to open the command line interface on your computer depends on the operating system. For Windows users, press the start button and look for "Command Prompt", or simply write "cmd" in the search field.
Navigate to the folder that contains the file "myfirst.js", the command line interface window should look something like this:
C:\Users\Your Name>_

Initiate the Node.js File

The file you have just created must be initiated by Node.js before any action can take place.
Start your command line interface, write node myfirst.js and hit enter:
Initiate "myfirst.js":
C:/Users/Your Name>node myfirst.js
Now, your computer works as a server!
If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in return!
Start your internet browser, and type in the address: http://localhost:8080