0

If one wants to jump start a project in Node.js with express. one would use express-generator. After creating a new project your file tree will look like this

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.pug
    ├── index.pug
    └── layout.pug

One thing that stood out for me is that to run the app you need to do node bin/www or a predefined shortcut npm run. My question is why would one use the www the way it is and not add a .js extension and remove #!/usr/bin/env node from the top of the file? Are there any benefits of doing it this way or is it a personal preference?

Anton Kastritskiy
  • 1,248
  • 1
  • 11
  • 23
  • The bin\ directory serve as a location where you can define your various startup scripts, the www is an example on how it should looks like, ultimately you could have startup script like test, stop or restart etc. Having this structure allows you to have different configurations without touching the app.js. http://stackoverflow.com/questions/23169941/what-does-bin-www-do-in-express-4-x – Ratan Kumar Apr 02 '17 at 14:51
  • @RatanKumar Thank you for your comment. I got this bit, my question is why is it `www` instead of `www.js` and if there are benefits of doing it this way? – Anton Kastritskiy Apr 02 '17 at 17:30

1 Answers1

1

Let's look at the first line of the bin/www file:

#!/usr/bin/env node

This shebang tells the *nix operating system how to interpret the file if you try to run it as a program.

So this file can be started as a program. And in Linux traditionally executable files do not have an extension.

stdob--
  • 28,222
  • 5
  • 58
  • 73
  • Thank you for the answer, I understood that this line tells the computer how to execute this code, my question why would you do this rather than putting `.js` extension on it. – Anton Kastritskiy Apr 02 '17 at 23:37
  • @AntK : `...Linux traditionally executable files do not have an extension...` – stdob-- Apr 03 '17 at 06:22
  • I am aware of it, thank you. I was just wondering why this is preferable over having `"start": "node bin/www.js"`, where your `www.js` could also be linted, tested and other things that you can do to js files in your application. – Anton Kastritskiy Apr 03 '17 at 21:17
  • @AntK I think that the main benefit is that you can start the service just from the terminal or cron etc: `/var/www/projects/express-app/bin/www`. – stdob-- Apr 03 '17 at 21:26
  • But also nothing is stopping you from typing `node /var/www/projects/express-app/bin/www.js`, to me this seems like rather an inconvenience, yet I probably missing on something – Anton Kastritskiy Apr 04 '17 at 00:06
  • @AntK It's not Linux way because: `...Linux traditionally executable files do not have an extension...` – stdob-- Apr 04 '17 at 04:36