Setting up a development environment
Install Node.js
Node.js can be installed in different ways and platforms. Official packages for all the major platforms are available https://nodejs.org/en/download/. One very convenient way to install Node.js is through a package manager. In this case, every operating system has its own.
Task
Install node to your computer.
When Node.js is installed, you'll have access to the node executable program in the command line. You can check installed node version with -v
attribute.
1 2 |
|
Editors
While you're free to use whatever editor you wish to use, Visual Studio Code will be used in this course materials.
First Hello!
Create a one hello.js
JavaScript file:
1 |
|
Run it with node:
1 2 |
|
You should see "Hello from Node!" printed out to the console where you ran the command above.
Nice
You can run JavaScript files in server side easily with Node.js!
Creating a project
Each Node.js project is actually a package similar to the packages found from Node Package Manager - NPM. Each package is defined by having a package.json
file in the root of the project directory. It defines the package information, lists dependencies along their versions and exposes a bunch of scripts that can be ran as build commands.
First create a folder (name it for example hello
) and go that folder. Give npm init
command to create a package.json
file.
1 2 3 |
|
After that you will need to answer a few basic questions and your project initialization package.json
file will be generated.
1 2 3 4 5 6 7 8 9 |
|
Read more: Creating a package.json file
Generated package.json
tells that application starting point is index.js
.
1 2 3 4 5 6 7 8 9 10 11 |
|
So, you need to create your JavaScript file and name it index.js
.
Create a index.js
file and type below programming inside it.
1 |
|
Remember save file in the same folder as package.json
.
Running a project
The usual way to run a Node program is to run the node
globally available command and pass the name of the file you want to execute.
Use command line and go to your project folder.
Give a below command to run your project and your first Node application should be executed.
1 2 |
|
Modify your package.json
to use npm
script to start your project.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Now you can launch your project with npm start
command in command line. This is how commands should be executed to the Node projects.
1 2 3 4 5 6 |
|
Read more about package.json
from here: What is the file package.json?
Note
You can create package.json
file easily (without any questions) with command npm init -y
.
Installation complete
Ok, now your Node.js installation should be complete and you can start learning more!
Read more
Goals of this topic
Succesfully
- Installed both Node.js & npm on your work machine.
- Ran a basic Node.js application on your work machine.