https://www.w3schools.com/nodejs/default.asp
Node.js is an open source server framework.
Node.js allows you to run JavaScript on the server.
Start learning Node.js now »Click on the "Run example" button to see how it works.
In this tutorial there will be some examples that are better explained by displaying the result in the command line interface.
When this happens, The "Show Node.js" tool will show the result in a black screen on the right:
Click on the "Run example" button to see how it works.
Node.js has a set of built-in modules.
Download Node.js from the official Node.js web site: https://nodejs.org
Node.js uses asynchronous programming!
A common task for a web server can be to open a file on the server and return the content to the client.
Here is how PHP or ASP handles a file request:
Here is how Node.js handles a file request:
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.
The official Node.js website has installation instructions for Node.js: https://nodejs.org
Once you have downloaded and installed Node.js on your computer, lets try to display "Hello World" in a web browser.
Create a Node.js file named "myfirst.js", and add the following code:
myfirst.js
Save the file on your computer: C:\Users\Your Name\myfirst.js
The code tells the computer to write "Hello World!" if anyone (e.g. a web browser) tries to access your computer on port 8080.
For now, you do not have to understand the code. It will be explained later.
Node.js files must be initiated in the "Command Line Interface" program of your computer.
How to open the command line interface on your computer depends on the operating system. For Windows users, press the start button and look for "Command Prompt", or simply write "cmd" in the search field.
Navigate to the folder that contains the file "myfirst.js", the command line interface window should look something like this:
C:\Users\Your Name>_
The file you have just created must be initiated by Node.js before any action can take place.
Start your command line interface, write node myfirst.js
and hit enter:
Initiate "myfirst.js":
C:/Users/Your Name>node myfirst.js
Now, your computer works as a server!
If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in return!
Start your internet browser, and type in the address: http://localhost:8080
Consider modules to be the same as JavaScript libraries.
A set of functions you want to include in your application.
Node.js has a set of built-in modules which you can use without any further installation.
Look at our Built-in Modules Reference for a complete list of modules.
To include a module, use the require()
function with the name of the module:
Now your application has access to the HTTP module, and is able to create a server:
You can create your own modules, and easily include them in your applications.
The following example creates a module that returns a date and time object:
Create a module that returns the current date and time:
Use the exports
keyword to make properties and methods available outside the module file.
Save the code above in a file called "myfirstmodule.js"
Now you can include and use the module in any of your Node.js files.
Use the module "myfirstmodule" in a Node.js file:
Notice that we use ./
to locate the module, that means that the
module is located in the same folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
C:\Users\Your Name>node demo_module.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the
require()
method:
The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
Use the createServer()
method to create an
HTTP server:
The function passed into the http.createServer()
method, will be executed when someone tries to access the
computer on port 8080.
Save the code above in a file called "demo_http.js", and initiate the file:
Initiate demo_http.js:
C:\Users\Your Name>node demo_http.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
If the response from the HTTP server is supposed to be displayed as HTML, you should include an HTTP header with the correct content type:
The first argument of the res.writeHead()
method is the status code, 200 means
that
all is OK, the second argument is an object containing the response headers.
The function passed into the http.createServer()
has a req
argument that represents the request from the
client, as an object (http.IncomingMessage object).
This object has a property called "url" which holds the part of the url that comes after the domain name:
demo_http_url.js
Save the code above in a file called "demo_http_url.js" and initiate the file:
Initiate demo_http_url.js:
C:\Users\Your Name>node demo_http_url.js
If you have followed the same steps on your computer, you should see two different results when opening these two addresses:
There are built-in modules to easily split the query string into readable parts, such as the URL module.
Split the query string into readable parts:
Save the code above in a file called "demo_querystring.js" and initiate the file:
Initiate demo_querystring.js:
C:\Users\Your Name>node demo_querystring.js
The address:
http://localhost:8080/?year=2017&month=July
Read more about the URL module in the Node.js URL Module chapter.
The Node.js file system module allow you to work with the file system on your computer.
To include the File System module, use the
require()
method:
Common use for the File System module:
The fs.readFile()
method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Save the code above in a file called "demo_readfile.js", and initiate the file:
Initiate demo_readfile.js:
C:\Users\Your Name>node demo_readfile.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile()
method appends specified content to a file. If the
file does not exist, the file will be created:
Create a new file using the appendFile() method:
The fs.open()
method takes a "flag" as the second argument, if the
flag is "w" for "writing", the specified file is opened for writing. If the file
does not exist, an empty file is created:
Create a new, empty file using the open() method:
The fs.writeFile()
method replaces the specified file and content if it exists.
If the file does not exist, a new file, containing the specified content, will
be created:
Create a new file using the writeFile() method:
The File System module has methods for updating files:
fs.appendFile()
fs.writeFile()
The fs.appendFile()
method appends the specified content at the end of the specified file:
Append "This is my text." to the end of the file "mynewfile1.txt":
The fs.writeFile()
method replaces the specified file and content:
Replace the content of the file "mynewfile3.txt":
To delete a file with the File System module, use the fs.unlink()
method.
The fs.unlink()
method deletes the specified file:
Delete "mynewfile2.txt":
To rename a file with the File System module, use the fs.rename()
method.
The fs.rename()
method renames the specified file:
Rename "mynewfile1.txt" to "myrenamedfile.txt":
You can also use Node.js to upload files to your computer.
Read how in our Node.js Upload Files chapter.
The URL module splits up a web address into readable parts.
To include the URL module, use the require()
method:
Parse an address with the url.parse()
method, and it will return a URL object with each part of the address as
properties:
Split a web address into readable parts:
Now we know how to parse the query string, and in the previous chapter we learned how to make Node.js behave as a file server. Let us combine the two, and serve the file requested by the client.
Create two html files and save them in the same folder as your node.js files.
summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love
the sun!</p>
</body>
</html>
winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love
the snow!</p>
</body>
</html>
Create a Node.js file that opens the requested file and returns the content to the client. If anything goes wrong, throw a 404 error:
demo_fileserver.js:
Remember to initiate the file:
Initiate demo_fileserver.js:
C:\Users\Your Name>node demo_fileserver.js
If you have followed the same steps on your computer, you should see two different results when opening these two addresses:
http://localhost:8080/summer.html
Will produce this result:
Summer
I love the sun!
http://localhost:8080/winter.html
Will produce this result:
Winter
I love the snow!
NPM is a package manager for Node.js packages, or modules if you like.
www.npmjs.com hosts thousands of free packages to download and use.
The NPM program is installed on your computer when you install Node.js
NPM is already ready to run on your computer!
A package in Node.js contains all the files you need for a module.
Modules are JavaScript libraries you can include in your project.
Downloading a package is very easy.
Open the command line interface and tell NPM to download the package you want.
I want to download a package called "upper-case":
Download "upper-case":
C:\Users\Your Name>npm install upper-case
Now you have downloaded and installed your first package!
NPM creates a folder named "node_modules", where the package will be placed. All packages you install in the future will be placed in this folder.
My project now has a folder structure like this:
C:\Users\My Name\node_modules\upper-case
Once the package is installed, it is ready to use.
Include the "upper-case" package the same way you include any other module:
Create a Node.js file that will convert the output "Hello World!" into upper-case letters:
Save the code above in a file called "demo_uppercase.js", and initiate the file:
Initiate demo_uppercase:
C:\Users\Your Name>node demo_uppercase.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
Node.js is perfect for event-driven applications.
Every action on a computer is an event. Like when a connection is made or a file is opened.
Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file:
Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own events.
To include the built-in Events module use the require()
method. In addition, all event properties and methods are an instance of an
EventEmitter object. To be able to access these properties and methods, create
an EventEmitter object:
You can assign event handlers to your own events with the EventEmitter object.
In the example below we have created a function that will be executed when a "scream" event is fired.
To fire an event, use the emit()
method.
There is a very good module for working with file uploads, called "Formidable".
The Formidable module can be downloaded and installed using NPM:
C:\Users\Your Name>npm install formidable
After you have downloaded the Formidable module, you can include the module in any application:
Now you are ready to make a web page in Node.js that lets the user upload files to your computer:
Create a Node.js file that writes an HTML form, with an upload field:
This code will produce an HTML form:
Include the Formidable module to be able to parse the uploaded file once it reaches the server.
When the file is uploaded and parsed, it gets placed on a temporary folder on your computer.
The file will be uploaded, and placed on a temporary folder:
When a file is successfully uploaded to the server, it is placed on a temporary folder.
The path to this directory can be found in the "files" object, passed as the
second argument in the parse()
method's callback function.
To move the file to the folder of your choice, use the File System module, and rename the file:
Include the fs module, and move the file to the current folder:
The Nodemailer module makes it easy to send emails from your computer.
The Nodemailer module can be downloaded and installed using npm:
C:\Users\Your Name>npm install nodemailer
After you have downloaded the Nodemailer module, you can include the module in any application:
Now you are ready to send emails from your server.
Use the username and password from your selected email provider to send an email. This tutorial will show you how to use your Gmail account to send an email:
And that's it! Now your server is able to send emails.
To send an email to more than one receiver, add them to the "to" property of the mailOptions object, separated by a comma:
Send email to more than one address:
To send HTML formatted text in your email, use the "html" property instead of the "text" property:
Send email containing HTML: