babel and pm2 for es6 applications

Babel compiles the es6 javascript into es5 and run it. pm2 auto restarts the app server whenever changes are made to the code base. Install them globally from command line.

sudo npm install -g babel
sudo npm install -g pm2

Create a sample http server with es6 features, the keyword let and the arrow function. app.js

let http = require("http");
let fs = require("fs");
let fileToServe = "./readme.txt";
http.createServer((req, res) => {
	fs.readFile(fileToServe, (err, data) => {
		if(err) console.log("Error reading the file.", err);
console.log("Server running at: " + "localhost:3000");

Create a pm2 config file to specify the app will run using babel-node. pm2_config.json

  "apps" : [{
    "name"        : "sample-app",
    "script"      : "./app.js",
    "watch"       : true,
    "exec_interpreter" : "babel-node",
  	"exec_mode"        : "fork",

Start the server using pm2 and feeding it with pm2 config file created from the above.

pm2 start pm2_config.json

The keyword let and the arrow function such as (req, res) => {} are new features in es6, if you run it with node, it will error out. You want to keep node with es5 and want to try out the es6 features. Babel comes in handy here. It will compile the es6 code to es5 and then run it. pm2 speeds up the development time by auto restarting the app when changes are made to the code base.

Other essential pm2 commands.

pm2 start <app_name>
pm2 list
pm2 restart <app_name|id|all>
pm2 delete <app_name|id|all>

Search within Codexpedia

Custom Search

Search the entire web

Custom Search