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

Vue+Openlayer uses modify to modify the complete code of the element

Vue+Openlayer uses modify to modify elements. The...

HTML unordered list bullet points using images CSS writing

Create an HTML page with an unordered list of at l...

WeChat applet custom tabbar component

This article shares the specific code of the WeCh...

How to deploy springcloud project with Docker

Table of contents Docker image download Start mys...

Use of Linux sed command

1. Function Introduction sed (Stream EDitor) is a...

Reasons and solutions for not being able to detect array changes in Vue2

Table of contents Workaround Why can't I moni...

Use of Vue filters and custom instructions

Table of contents Filters 01.What is 02. How to d...

Win10 installation Linux system tutorial diagram

To install a virtual machine on a Windows system,...

W3C Tutorial (10): W3C XQuery Activities

XQuery is a language for extracting data from XML...

Install Kafka in Linux

Table of contents 1.1 Java environment as a prere...

Learn v-model and its modifiers in one article

Table of contents Preface Modifiers of v-model: l...