After Downloading and Installing node in your machine, we will start with the small example of Node server setup.
Open the VScode or Visual Studio, and create project in Node.js
npm init
After running the above command, it will ask a couple of questions in the command prompt such as package name, version, entry point, author and more.
> npm init package name: (index) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC)
To prevent asking the above questions, we can use the below command it will create a package.json file with the default configuration for us and later we can modify it.
npm init -y
Scripts object in `package.json` stores information in `key-value` pairs and helps us to maintain different scripts to run our application in multiple environments. such as `dev environment`, `prod environment`, `run test cases` and more.
"scripts": { "start": "node index.js" },
let http = require("http"); http .createServer(function (req, res) { res.writeHead(200, { "Content-Type": "text/html" }); res.end("Server Listening..."); }) .listen(3002);
After adding code, save the file named with `index.js`.
Navigate to files location and open (Terminal/Command prompt).
Type the below command to run the code.
node run start
we are done! now, navigate to any browser type: `http://locahost:3002/`
your node server is up and running on your machine, ready to accept new incoming traffic on it.
if we update our code in the `index.js` file it will not reflect the changes because the `node index.js` command is not aware any change has been done in our codebase.
For ex:- `Server Listening...` to `Server Listening on 3002`
To overcome this issue we can use `nodemon` package, Nodemon is a tool that restarts automatically Node.js applications when file changes are detected.
To install `nodemon` package in your project. use the below command:
npm install nodemon
After installing Nodemon, we need to update `Scripts Object in package.json`.
// Then "scripts": { "start": "node index.js" } // Now "scripts": { "start": "nodemon index.js" }
Stop your application by pressing `ctrl + c` on Windows and `control + c` on Mac.
npm run start
Now, if you update your code in the `index.js` file it will reflect the changes instantly as we save the file. Nodemon detects the changes and restarts the server.