Writing your first NodeJS Script
●
First, create a folder inside your C:\ drive. Name
it “citcs”. See image below for reference
●
Inside the CITCS folder, I want you to create a
new file. Name it “[Link]”.
– You may use notepad++ or VS Code to create a js
file. Just make it sure to save the file inside the citcs
folder.
– See next slide for reference
●
Open your command prompt
●
In your command prompt window, type the following:
– cd \
– cd citcs
– npm init
●
For package name, type “hello_world”
●
For version, skip it, just press enter
●
For description, enter “nodejs exercises”
●
For entry point, skip it, press enter.
●
For the succeeding entry, skip it.
●
For author, enter your name.
●
If being asked if everything is okay, just press enter.
●
Output
●
Let’s install the nodejs express framework.
– In the command prompt, type “npm install express -
s”
●
Open your entire “citcs” folder in VsCode Editor
●
Click the “[Link]” file from the file explorer window inside the
VsCode Editor
●
Type the following inside the [Link] file
●
In JavaScript ES6, semicolon is not required at
the end of your js code.
●
We defined the specific port number of our http
server using const port = 8000
●
To run our nodejs script, simply type node [Link] in the command line
If your code is correct, we
should have similar output.
●
Let say you want to change the port number of
the http server. Changing it to 8888
●
Okay,here’s the thing you need to keep in mind.
●
Everytime you make some changes in your
nodejs script file, you need to restart the server.
●
To restart the http server, go the command line
window the simultaneously press ctrl + c
●
Then re-run the http server by typing node [Link] again in the
command line.
●
This task is tedious and we want to code smart,
not code hard.
●
We will install another extension for nodejs to
automate this task.
●
This extension is nodemon.
●
In the command line, type npm install nodemon -s -g
●
To use nodemon, simple type nodemon [Link] in the command line
●
To test the nodemon, make any changes in
your [Link] file and watch how nodemon
handle the changes you made in the nodejs
script file.
●
Here, I change the port number to 9999 and nodemon automatically restart the http
server for me.