Basic Node js, Create Local Server With Javascript

in #utopian-io8 years ago (edited)

Nodejs-2-562x309@2x-op.png

image-source :

This tutorial will discuss node js. maybe you've heard node js but have not got any tutorial from basic about node js. with js node we can use javascript as server language. so we can create a pure application with javascript. without Php or python or ruby. if we have been using javascript as a client language, now we can also use it as a server language

What is Node Js?

Nodejs is created with the same engine chrome browser developed by google, its open source. . node js have non-blocking properties meaning that in node js. we perform a function in parallel and when we are done with a function we can put callback, node js will not wait until task "A" has finished. node js will execute other functions simultaneously. Now you can download nodejs on its official website https://nodejs.org/

Create Local Server With Javascript

Now you can create a folder, in this tutorial the name of folder is Nodejs, open command prompt here , and you can see your nodejs version, if its version already appears it means nodejs has been installed

Screenshot_2.png

Create Server.js

If javascript is usually used for the client language, in this section we will create a local server server, using only javascript language.


var http = require('http');
function handleRequest(request,response){
    response.end("Hello World!")
}
var server = http.createServer(handleRequest);
server.listen(3000, function(){
    console.log("it's running in localhost:3000")
})

var http = require( ' http ' ) : Http is a module that automatically comes by itself when you install node js. we can install additional modules from NPM ( Node Package Manager )
var server = http.createServer( handleRequest ) :This code is useful for creating server. its function name is createServer ( ) and we passing the function to handle the request, its function name is handleRequest. the function name is up to you, but keep it relevant to the functionality of the function.


function handleRequest(request,response){
    response.end("Hello World!")
}

In the handleRequest function, we will accept two parameters. Request and Response


server.listen(3000, function(){
    console.log("it's running in localhost:3000")
})

This is the method to run its server, this tutorial runs on port 3000. I will run a console log to make sure our server is running properly . to run the server..
D:\Nodejs>node server.js
Screenshot_3.png
Screenshot_4.png

We have created localserver only by using javascript language.

Insert html file

In the website of course we not only want to run the server, but we want to insert the file, such as html.


var http = require('http');
var fs   = require('fs');
function handleRequest(request,response){
    response.writeHead(200,{'Content-Type': 'text/html'});
    fs.readFile('./index.html',null,function(error,data){
        if(error){
            response.writeHead(400);
            response.write("File not Found!")
        }else{
            response.write(data)
        }
    });
}
var server = http.createServer(handleRequest);
server.listen(3000, function(){
    console.log("it's running in localhost:3000")
})

var fs = require( 'fs' ) : This is module to readfile .that automatically comes by itself when you install node js
response.writeHead(200,{'Content-Type': 'text/html'})
we will put code 200 means succeed and no problem. then we give {'Content-Type': 'text/html'} because this file has html
fs.readFile('./index.html',null,function(error,data) { } : we read the file with readFile . we read file index.html , we can add options in second parameter, but in this tutorial we pass null, cause we dont pass anything. and then we put callback function with two parameters . they are error and data ( error,data ), and then and we can make a simple logic to check if the index.html file is successfully read. if an error then writeHead ("file not found"). the result will be like this..
Screenshot_5.png

That's was Great...! we have finished making the server and read the html file by using only javascript language. we have created javascript as the language serve. so many of me .. hopefully this tutorial is useful for those of you who just learned node.js



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @alfarisi94 I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

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

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.080
BTC 59313.08
ETH 1551.67
USDT 1.00
SBD 0.47