readme sample

Whenever you creates a git repo, you should care to create a good readme.
Below is the sample that I’ve found on bitbucket which is sweet and simple :

# README #

This README would normally document whatever steps are necessary to get your application up and running.

### What is this repository for? ###

* Quick summary
* Version
* [Learn Markdown](https://bitbucket.org/tutorials/markdowndemo)

### How do I get set up? ###


* Summary of set up
* Configuration
* Dependencies
* Database configuration
* How to run tests
* Deployment instructions

### Contribution guidelines ###

* Writing tests
* Code review
* Other guidelines

### Who do I talk to? ###

* Repo owner or admin
* Other community or team contact

Random bg Color

Find on GitHub

Play with background colors on any HTML elements.

Usage

1. Include

<script src="path/to/your/directory/random-bg-color.js">
OR
<script src="path/to/your/directory/random-bg-color.min.js">

2.

<script type="text/JavaScript">bgColors.apply();</script>

Options

By default if no element is given, colors would be applied to tag.You can pass list of elements by their classes or ids or by their name itself. e.g.

1. Single element

bgColors.targetElements = '#myId'; or bgColors.targetElements = ['#myId'];

2. Multiple elements

bgColors.targetElements = ['#myId','#anotherId','#onemoreId'];

3. Mixed elements

bgColors.targetElements = ['#myId','.myClass','.anotherClass','span'];

You can also pass selected list of colors e.g.

1. Multiple colors

bgColors.colors = ['#1abc9c', '#d3d3d3','#ffeeee'];

2.Only one color

bgColors.colors = '#1abc9c' or bgColors.colors = ['#1abc9c'];

More options

1. If you want to change colors without page reload set bgColors.autoChange value true. e.g.

bgColors.autoChange=true;

2. You can set interval (in miliseconds) if you has set autoChange true. e.g.

bgColors.autoChangeDelay = 2000;// Only works if autoChange is true. 

Combining all along

<script type="text/javascript">
bgColors.targetElements = ['.t1','#g1','div'];
bgColors.colors = ['#1abc9c', '#d3d3d3'];
bgColors.apply();</script>
See Live Demo on fiddle

ExpressJs – a piece of cake

I’ve gathered some useful resources intended to help you for better understanding in Express.js.
This is aimed at people who have some familiarity with Node.js.To know how to run Node scripts and can install packages with npm you don’t have to be an expert, though — I promise.

Ok! lets start,

Express.js is a web framework which is based on the core Node.js http module and Connect components. Those components are called middlewares. They are the cornerstone of the framework’s philosophy, i.e., configuration over convention.

Like any abstraction, Express hides difficult bits and says "don't worry, you don't need to understand this part". It does things for you so that you don’t have to bother. In other words, it’s magic.you might not understand the inner workings of Express. This is like driving a car; I drive a car just fine without intimate knowledge of its workings, but I’d be better off with that knowledge. What if things break? What if you want to get all the performance you can out of the car? What if you have an insatiable thirst for knowledge?

Bored?? Okay Okay, so let’s move to some practicals and understand Express.js.

I’m considering Express.js is a piece of cake.

Express is a piece of cake

So let’s understand Express from the bottom, with Node.

Bottom layer: Node’s HTTP server (Creating Server)

Node has an HTTP module which makes a pretty simple abstraction for making a web server.

How? Like this example below :

/*----Create a file server.js----*/
// Require http module
var http = require("http");

// Build the server
var app = http.createServer(function(request, response) {
  response.writeHead(200, {
    "Content-Type": "text/plain"
  });
  response.end("Hello world!");
});

// Start that server
app.listen(3000, "localhost");
console.log("Server running at http://localhost:3000");

Run the app and check the output.You’ll get a response of “Hello world!”

code 01 output

if you visit localhost:3000/ in your browser. You’ll get the same response no matter what, too. You can try visiting localhost:3000/mango or localhost:3000/?fruit=mango, and it’s like talking to a brick wall: “Hello world!”

Builtin require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a javascript file, executes the file, and then proceeds to return the exports object.

hmm., that means:

  1. The first line uses the require function to load a built-in Node module called http. It puts this fabulous module inside of a variable called http.
  2. Then we put a server in a variable called app by using http.createServer. This takes a function that listens for requests.
  3. I’ll explain this in a minute because they’re Super Duper Important. Skip over it for now.

  4. The last thing we do is tell the server to listen for requests coming in on port 3000, and then we just log that out. And then we’re up.

Okay, back to the skipped part the request handler function.

The request handler

I should say that there’s a bunch of cool HTTP stuff in here that I don’t think is relevant to learning Express. If you’re interested, you can look at the docs for the HTTP module because they have a bunch of stuff.

Whenever we make a request to the server, that request handler function is called. If you don’t believe me, try putting a console.log in there. You’ll see that it logs out on your terminal every time you load a page.

request is a request that comes from the client. In many other apps, you’ll see this shortened to req. Let’s look at it. To do that, we’ll modify the above request handler a bit:

// Build the server
var app = http.createServer(function(request, response) {

  // Build the result
  var result = "";
  result += "Request URL: " + request.url + "\n";
  result += "Request type: " + request.method + "\n";
  result += "Request headers: " + JSON.stringify(request.headers) + "\n";

  // Send result
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end(result);

});

Restart the server and reload localhost:3000.

node Http module

You’ll see what URL you’re requesting, that it’s a GET request, and that you’ve sent a number of cool headers like the user-agent and more magical HTTP stuff! If you visit localhost:3000/honey, you’ll see the request URL change. If you visit it with a different browser, the user-agent will change. If you send it a POST request, you’ll see the method change.

Node.js applications are stored in memory, and if we make changes to the source code, we need to restart our app.

The response is the next part. Just like the prior argument is often shortened, this is often shortened to the three-letter res. With each response, you get the response all ready to send, and then you call response.end. Eventually, you must call this method; even the Node docs say so. This method does the actual sending of data. You can try making a server where you don’t call it, and it just hangs forever.

Before you send it out, you’ll want to write some headers. In our example, we do this:

response.writeHead(200, { "Content-Type": "text/plain" });

This does two things. First, it sends HTTP status code 200, which means "OK, everything is good”. Then, it sets some response headers. In this case, it’s saying that we’re sending back the plaintext content-type. We could send other things like JSON or HTML.

Alright, if you thirst for more you could do something like this.

// Build the server
var app = http.createServer(function(request, response) {

  // Homepage (Default)
  if (request.url == '/') {
    response.writeHead(200, { 'Content-Type': 'text/html'});
    response.end("<h1>Welcome to the homepage!</h1>");
  }

  // About page
  else if (request.url == '/about') {
    response.writeHead(200, { 'Content-Type': 'text/plain'});
    response.end('Welcome to the about page!');
  }

  // 404'd!
  else {
    response.writeHead(404, {'Content-Type': 'text/plain'});
    response.end('404 error! Page not found.');
  }
});

You could clean this up and make it pretty, or you could be hardcore like the npm.org folks and tough it out with vanilla Node. But you could also build a framework…a framework like Express.

res.send() is a special Express.js method that conveniently goes beyond what our old friend from core http module res.end() does. For example, the former automatically adds a Content-Length HTTP header for us. It also augments Content-Type based on the data provided to it

Middle layer: Middlewares (Using Express.js)

Middleware is a special function that allows for better code organization and reuse. Some of the middleware is packaged as third-party (NPM) modules and can be used right out of the box. Other times, we can write our own custom middleware. In both cases the syntax is app.use().

Okay, I explain this by using this code.

Let’s say we wanted to write the “hello world” app that we had above, but with Express this time. Don’t forget to install Express (npm install, baby). Once you’ve done that, the app is pretty similar.

// Require the ingredients we need
var express = require("express");
var http = require("http");

// Build the app
var app = express();

// Add some middleware
app.use(function(request, response) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Hello world!");
});

// Start it up!
http.createServer(app).listen(3000);

So let’s step through this.

First, we require Express. We then require Node's HTTP module just like we did before. We’re ready.

Then we make a variable called app like we did before, but instead of creating the server, we call express(). What’s going on? What is this madness?

We then add some middleware — it’s just a function. We pass this to app.use, and this function looks an awful lot like the request handlers from above.

Then we create the server and start listening. http.createServer, took a function before, so guess what — app is just a function. It’s an Express-made function that starts going through all the middleware until the end. But it’s just a request handler like before.

(Worth noting that you might see people using app.listen(3000), which just defers to http.createServer. That’s just a shorthand.)

In my language Middlewares are ‘Just a request handlers’ that starts from the top to the next, and to the next, and so on.

Here’s what middleware basically looks like:

function IamFuncMiddleware(request, response, next) {
   // Do stuff with the request and response.
   // When we're all done, call next() to defer to the next middleware.
   next();
}
When writing your own middleware, don’t forget to call the next() callback function. Otherwise, the request will hang and time out.

When we restart our server, we start at the topmost middleware and work our way to the bottom. So if we wanted to add simple logging to our app, we could do it!

var express = require("express");
var http = require("http");
var app = express();

// Logging middleware
app.use(function(request, response, next) {
  console.log('%s %s — %s', (new Date).toString(), request.method, request.url);
  next();
});
// Homepage
app.use(function(request, response, next) {
  if (request.url == "/") {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.end("Welcome to the homepage!\n");
    // The middleware stops here.
  } else {
    next();
  }
});

// About page
app.use(function(request, response, next) {
  if (request.url == "/about") {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.end("Welcome to the about page!\n");
    // The middleware stops here.
  } else {
    next();
  }
});

// 404'd!
app.use(function(request, response) {
  response.writeHead(404, { "Content-Type": "text/plain" });
  response.end("404 error!\n");
});

http.createServer(app).listen(3000);

If you run this app and visit localhost:3000, you’ll see that your server is logging some stuff and you’ll see your pages.

While you can totally write your own, there’s a ton of middleware out there. Let’s remove our logger and use Morgan, a nice logger for Express. Simply do npm install morgan

Top layer: Routes (Express Routes)

We’ve finally arrived at top layer of our piece of cake.Ohh.. the middle layers on soft and spongy bottom layer was too delicious. 😀

Routing is a way to map different requests to specific handlers. In many of the above examples, we had a homepage and an about page and a 404 page. We’d basically do this with a bunch of if statements in the examples.

But Express is smarter than that. Express gives us something called “routing” which I think is better explained with code than with English:

var express = require("express");
var http = require("http");
var app = express();

app.all("*", function(request, response, next) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  next();
});

app.get("/", function(request, response) {
  response.end("Welcome to the homepage!");
});

app.get("/about", function(request, response) {
  response.end("Welcome to the about page!");
});

app.get("*", function(request, response) {
  response.end("404!");
});

http.createServer(app).listen(3000);

ooh. That’s looks more tasty.

Routes can be either good old web pages or REST API endpoints. In both cases the syntax is similar: we use app.VERB(), where VERB() is an HTTP method such as GET, POST, DELETE, PUT, OPTIONS, or PATCH.The first argument is a path, like /about or /. The second argument is a request handler similar to what we’ve seen before.

The browser makes a GET request when you navigate it to some page, so at the very least your server should process GET requests.

These routes can get smarter, with things like this:

app.get("/fruit/:which", function(req, res) {
  res.end("My favorite fruit is, " + req.params.which+ ".");
  // Fun fact: this has security issues
});

Restart your server and visit localhost:3000/fruit/mango for the following message:

top layer

However, starting with Express.js v4.x, using the new Router class is the recommended way to define routes, via router.route(path).

The router.route(path) method is used to chain HTTP verb methods. For example, in a create, read, update, and delete (CRUD) server that has POST, GET, PUT, and DELETE endpoints for the /fruit/:which URL (e.g., /fruit/mango), we can use the Router class as follows:

var express = require('express');
var router = express.Router();
router
.route('/fruit/:which')
.all(function(request, response, next){
// This will be called for request with any HTTP method
})
.post(function(request, response, next){
//do something
})
.get(function(request, response, next){
//do something
})
.put(function(request, response, next){
//do something
})
.delete(function(request, response, next){
//do something
});
Request handler in express way:

Request handlers in Express.js are strikingly similar to callbacks in the core Node.js http.createServer() method,Because they’re just functions (anonymous, named, or methods) with req and res parameters.

Like :

var ping = function(req, res) {
console.log('ping');
res.end(200);
};
app.get('/', ping);

In addition, we can utilize the third parameter, next(), for control flow. Here is a simple example of two request handlers, zig and zag where the former just skips to the latter after printing a word zig

var zig = function(req, res, next) {
console.log('zig');
return next();
};
var zag = function(req, res) {
console.log('zag');
res.end(200);
};
app.get('/', zig,zag);

When a request comes on the / route, Express.js calls zig(), which acts as middleware in this case (because it’s in the middle!). Zig, in turn, when it’s done, calls zag with that finished response with res.end().


So, that’s all to create our very very simple home made expressJs cake. But of course this is not enough to make you a perfect chef. So keep on searching, practicing, exploring and one day you gonna your own world famous code restaurant. 😉

Good Luck!