Steps to create a WEBSERVER using NODE.JS

Steps to create a WEBSERVER using NODE.JS

What is nodejs

Node.js was released in May 2009 and developed by Ryan Dahl. It is a JavaScript runtime environment based on the Chrome V8 engine. It uses an event-driven, non-blocking I/O model to allow JavaScript to run on the server-side development platform. It makes JavaScript a scripting language on par with server-side languages ​​such as PHP, Python, Perl, and Ruby.
Node.js optimizes some special use cases and provides alternative APIs to make V8 run better in non-browser environments. The V8 engine executes Javascript very quickly and has very good performance. It is a platform built on the Chrome JavaScript runtime, which is used to easily build fast-response and easily scalable network applications.

Install NodeJS

nodejs official website

Check whether the installation is successful

$ node -v 
v14.16.1

How to create hello world using node?

1. Write a javascript script file

var foo = 'hello world'
console.log(foo)

2. Run the file

$ node filename

Note: The file cannot be named with node, and it is best not to use Chinese characters

How to read and write files using nodejs

// 1. Use require to load fs core usage module var file = require('fs')

// 2. Read the file file.readFile('hello.txt', function(error, data){
    // The file is stored in binary by default and needs toString
    if (error != null) {
        console.log('file dons not exits or read fail')
        return
    }
    console.log(data.toString())
})

// 3. Write file // File path file content callback function file.writeFile('hello.txt', 'hello world', function(error, data){
    if (error != null) {
        console.log('write fail')
        return
    }
    console.log('write success')
})

Creating a web server using nodejs

// 1. Use require to load the http core usage module var http = require('http')

// 2. http.createServer creates a server instance var server = http.createServer()

// 3. Create a request response server.on('request', function(request, response){
    console.log('Requesting interface...')
    response.write('Hello World')
    // The end method must end response.end()
})

// 4. Bind the port number to start the server server.listen(8090, function(){
    console.log('Server running at http://127.0.0.1:8090/')
})

How to return different data based on different request paths

var http = require('http')

var server = http.createServer();

server.on('request', function(request, response){
    // Get the request path var url = request.url
    
    // Return different information based on the request path if (url == '/') {
        response.end('index page')
    } else if (url == '/login') {
        response.end('login page')
    } else {
        response.end('404 page')
    }
  
})

server.listen('8081', function(){
    console.log('Server running at http://127.0.0.1:8081/');
})

Respond data to the front end

The response (return) content can only be binary data or a string

[
    {
        "name": "Iphone 12",
        "price": 6799
    },
    {
        "name": "MacBook Air M1",
        "price": 7999
    }
]

If you want to return the data to the page, you can only assemble the json data into a string

if (url == '/products') {
    var products = [
        {
            name : 'Iphone 12',
            price : 6799
        },
        {
            name : 'MacBook Air M1',
            price : 7999
        }
    ]
    response.end(JSON.stringify(products))
}

The above are the details of the steps to create a WEBSERVER using NODE.JS. For more information about creating a WEBSERVER with Node.js, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of the configuration of Express session and cookie module packages under the node.js platform
  • Practical application of angular2+node.js express packaging and deployment
  • How to install the latest version of Node.js on CentOS 8.2 server
  • Node.js+postman to simulate HTTP server and client interaction
  • Detailed explanation of how to configure the local Vue project to request the local Node.js server
  • Node.js three steps to implement a server and Express package use

<<:  Detailed explanation of MySQL injection without knowing the column name

>>:  Ubuntu 18.04 disable/enable touchpad via command

Recommend

js+css to realize three-level navigation menu

This article example shares the specific code of ...

How to allow all hosts to access mysql

1. Change the Host field value of a record in the...

MySQL database Load Data multiple uses

Table of contents Multiple uses of MySQL Load Dat...

Detailed explanation of the role of key in React

Table of contents Question: When the button is cl...

Practice using Golang to play with Docker API

Table of contents Installing the SDK Managing loc...

A useful mobile scrolling plugin BetterScroll

Table of contents Make scrolling smoother BetterS...

Analysis of Sysbench's benchmarking process for MySQL

Preface 1. Benchmarking is a type of performance ...

MySQL foreign key setting method example

1. Foreign key setting method 1. In MySQL, in ord...

How is a SQL statement executed in MySQL?

Table of contents 1. Analysis of MySQL architectu...

JavaScript to implement voice queuing system

Table of contents introduce Key Features Effect d...

js canvas realizes random particle effects

This article example shares the specific code of ...