Node.js basic Tutorial
Hi everyone,
I couldn't find a post about Node.js in steemit. So i decided to post a tutorial on it. I am trying to post basic but everything about Node.js. So let's get started.....
First of all, you need some answers before move on coding. You need the introduction of it to know what's really it is.
Introduction
What Node.js really is?
- Node.js is an open source server framework
- Node.js is free to use
- Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
- Node.js uses JavaScript on the server
What Can Node.js just Do?
Get Started
Download Node.js
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 code:
myfirst.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Save that file on your computer: C:\Users\Your Name\myfirst.js
The code tells to write "Hello World!" if anyone (e.g. a web browser) tries to access your computer on port 8080.
Command line interface on your computer depends on the operating system. For Windows users, the cmd is the command line interface
Navigate to the folder that contains the file "myfirst.js", the command line interface window look like this:
C:\Users\
Your Name
>_
Initiate the Node.js File
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 else tries to access your computer on port 8080, they will get a message "Hello World!" in return!
Start your internet browser from your computer, and type in the address: http://localhost:8080
Node.js Modules
What is a Module in Node.js?
Consider modules to be the same as JavaScript libraries.
A set of functions you want to include in your application.
Include Modules
To include a module, use the require()
function with the name of the module:
var http = require('http');
Now your application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Create Your Own Modules
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: exports.myDateTime = function () {
return Date();
};
Use the exports
keyword to make properties and methods available outside the module file.Save the code above in a file called "myfirstmodule.js"
Include Your Own Module
Now you can include and use the module in any of your Node.js files.
Use the module "myfirstmodule" in a Node.js file:
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Notice that we use ./
to locate the module, that means that the module is located in the same folder as the Node.js file.
Node.js HTTP Module
The Built-in HTTP Module
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:
var http = require('http');
Node.js as a Web Server 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:
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
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:
C:\Users\Your Name>node demo_http.jsIf you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
Add an HTTP Header
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 thevar http = require('http');
http.createServer(function (req, res) {
res.writeHead(200,
{'Content-Type':
'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
res.writeHead()
method is the status code, 200 means that all is OK, the second argument is an object containing the response headers
Read the Query String 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:var http = require('http');
http.createServer(function (req
, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url
);
res.end();
}).listen(8080);
C:\Users\Your Name>node demo_http_url.jsIf you have followed the same steps on your computer, you should see two different results when opening these two addresses:http://localhost:8080/summer Will produce this result:
/summerhttp://localhost:8080/winter will produce
/winter
Split the Query String
There are built-in modules to easily split the query string into readable parts, such as the URL module.
Save the code above in a file called "demo_querystring.js" and initiate the file:var http = require('http');
var
url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var
q = url.parse(req.url,
true).query;
var txt =q.year
+ " " +
q.month
;
res.end(txt);
}).listen(8080);
C:\Users\Your Name>node demo_querystring.jsThe address: http://localhost:8080/?year=2017&month=July Will produce this result:
2017 July
Node.js URL Module
The Built-in URL ModuleThe URL module splits up a web address into readable parts. To include the URL module, use the
require()
method:
var url = require('url');Parse an address with the
url.parse() method
, and it will return a URL object with each part of the address as properties:
Example:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'
Node.js File Server
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:
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Remember to initiate the file:C:\Users\Your Name>node demo_fileserver.jsIf 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 summer!
http://localhost:8080/winter.html
Will produce this result:
winter- I love the snow!
Files to Upload in Node.js
The Formidable Module
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 formidableAfter you have downloaded the Formidable module, you can include the module in any application:
var formidable = require('formidable');
Upload Files
Now you are ready to make a web page in Node.js that lets the user upload files to your computer: Step 1: Create an Upload Form Create a Node.js file that writes an HTML form, with an upload field: This code will produce an HTML form:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
Step 2: Parse the Uploaded File
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:
var http = require('http');
var
formidable = require('formidable');
http.createServer(function (req, res) {
if
(req.url
==
'/fileupload') {
var
form =
new
formidable.IncomingForm();
form.parse(req,
function
(err, fields, files) {
res.write('File uploaded');
res.end();
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
Step 3: Save the File 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:
var http = require('http');
var formidable = require('formidable');
var
fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var
oldpath = files.filetoupload.path;
var
newpath =
'C:/Users/
Your Name
/'
+ files.filetoupload.name;
fs.rename(oldpath, newpath,
function
(err) {
if
(err)
throw
err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
That's it for now.
Thanks, Everyone!!!
Stay tuned for my next contribution.........
nice work
Thanks a lot..
Upvoted👍
Thanks a lot
Good work!
Thank you so much for your comment!!
Nice tutorial.
thanks for your comment!!
Your contribution can't be approved yet. See the Utopian rules.
Please make the corrections and comment on this publication to review it.
[utopian-moderator]
You can check now.
Thank you for the contribution. It has been approved.
[utopian-moderator]
@sagorahmed i noticed you are not in utopian discord channel, but you have made a wonderful contribution, message on either steemi.chat or discord @mayowadavid so that you can join utopian on discord and also to submit and have your content rewarded
Congratulations @sagorahmed! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
You published a post every day of the week
Award for the number of upvotes
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Hey @sagorahmed I am @utopian-io. I have just upvoted you at 7% Power!
Achievements
Suggestions
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
Resteemed by @steemvote - send only 0.5 SBD to get your post resteemed to 2K follower and receive Bonus-Upvotes