To create a skeleton of a node js application this node js starter kit is followed best practices collected from experts.
If you are new to node js or you know node js, you can get benefit from this node js starter kit.
This starter kit is used express generator
to create a skeleton.
You can skip the step which you have previously applied.
Make sure you have installed Node JS on your computer
The latest version of node js is found here
Install
express generator
to quickly create a skeleton of node js applicationnpm i express-generator -g
Let’s start by creating a new app using
express generator
- First, open a folder where you want to store the app
this may refer as base folder later - Open
terminal
/command prompt
there - Run command:
express --view=ejs myApp
This will create a skeleton of your app
Here we will--view=ejs
for templating engine.myApp
are the app name and the directory which express generator will create
- First, open a folder where you want to store the app
Now Change The Directory To the newly created folder
this folder later refer as base folder later
cd myApp
Then install the dependencies
npm i
Install database management system
For the sake of relevance we use
mysql
in this here
Run command:npm i mysql --save
This will download the node js MySQL package
Use--save
flag to save it topackage.json
For any login based applications, we will use
cookie-session
to store sessionsRun command:
npm i cookie-session --save
Install
body-parser
for handlingPOST
requestRun command:
npm i body-parser --save
Now put all codes of
app.js
into an IIFEWe will change the app.js files created by default.
(function() { "use strict"; // Put all codes here })();
Now create a config file to hold all app & database configuration
Create a file called
config.json
at base folder
Inconfig.json
write all configurations in ajson
format
For example:{ "mysql": { "host": "localhost", "user": "root", "password": "password", "database": "db_name" }, "app" : { "port": 3000 } }
Here MySQL key will hold the MySQL configurations.
To use created
configs
in the appWe will import those files in
app.js
const fs = require('fs'); const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
Now
config
the variable will store all configurations fromconfig.json
Now we have to make some changes to
bin/www
file to start the app in this way- Import config file just like above
- Then change (usually line no
15
)
Fromvar port = normalizePort(process.env.PORT || '3000');
to
var port = normalizePort(process.env.PORT || config.app.port);
Then again change a line in
bin/www
From
server.listen(port);
to
server.listen(port, function() { console.log('Listening on port: ' + port); });
Then start the application by running the command
npm start
Your app is now running on port 3000
You can go to your browser in this location http://localhost:3000
- Now you can change
views/index.ejs
file to see it is working
Now you are all set to begin creating a node js application.