Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning node.js/express.js: What's the deal with bin/www?

I've seen tutorials for express.js such as this which starts from scratch with their own app.js file and forgoes using the express generator.

My question: for beginner who's trying to grasp just how to use these tools and make a basic web application should I be concerned with bin/www or should I just be defining the port within app.js?

The only functionality I currently understand in bin/www is setting the port. Is the express generator simply bloated with edge case functionality which is too much for a beginner?

like image 410
i3rendn4v05 Avatar asked Apr 15 '16 04:04

i3rendn4v05


People also ask

What does Node bin www do?

"scripts": { "start": "node ./bin/www" }, This is the code that allows you to run npm start for the app.

What is bin www file in Express?

The bin/ directory serves as a location where you can define your various startup scripts. The www is an example to start the express app as a web server.

Is it necessary to learn node JS for express js?

No, It isn't, ExpressJs is framework build on top of nodejs, as they are many framework in different programming language it is the same for Javascript in the backend side. In the nodejs world ExpressJS is the popular one, so in many books it's normal to talk about It, as Javascript was firstly build for the web.


2 Answers

Here is the reason, stated succinctly by an express maintainer:

So you can require('./app') from external files and get the express app that is not listening on any port (think unit tests and the like).

source

like image 92
cmikeb1 Avatar answered Oct 30 '22 11:10

cmikeb1


app.js

  • contains all the middleware(body-parser,morgan,etc) and routes.
  • it exports app object at the last.

www

  • here it creates a httpServer and passes app as the handler

var server = http.createServer(app);

  • besides also sets the port server.listen(port);
  • also sets the functions to be called if there is an error while starting the server: server.on('error', onError);

Explanation so, basically it removes all the create and start server code from your app.js and let you focus only on the application logic part. Note: If you see in package.json file you would note this:

"scripts": {   "start": "node ./bin/www" } 

this means if you type in terminal npm start then it will automatically start the ./bin/www file.

like image 25
Nivesh Avatar answered Oct 30 '22 10:10

Nivesh