Node. Getting started with JS is easy

Catalog

1. Flow and Pipeline

2. Web server output content

1.server output text information

2.server output an HTML file (effect)

3.server outputs data in JSON format

3. Modular Organization Code

4. Route

1. Flow and Pipeline

The concept of stream is not difficult to understand. For example, our usual front-end and back-end interactions are actually transformed into stream-in-stream interactions. We have talked about read and write of files before. Read and write of files are also the reflection of the operation of stream. This is if the pieces are special, we still need to buffer them.
We now command to operate basic operations
ls
ls | grep app
ls | grep app This command works on linux or mac, or git bash on windows.
If it is a windows command prompt, the corresponding command for finding files should be: dir | findstr app
Next, let's see the specific operation of downstream
Read files using streams:
//Import File Flow Module
var fs=require('fs');

//_u dirname is to get the current object
var myReadstream =fs.createReadStream(__dirname+'/readMe.txt');
//The encoding format can also be set directly to the second parameter of the function above
//Without utf-8 encoding, this object returns a buffer object, that is, the following chunk is a buffer object, with multiple buffers when there is a large amount of data
myReadstream.setEncoding('utf-8');

var data="";
//Setting up listeners for stream objects
myReadstream.on('data',function(chunk){
    
    //console.log(chunk);
    //Using data instead of outputting chunk directly does other things before it has finished reading
    data+=chunk;
    //You may not have finished reading before you start
})

myReadstream.on('end',function(){
    console.log(data);
})
What the above code reads is buffer Object, which is also the main reason for his performance improvement. If a muscle passes through, it will be processed into multiple pieces buffer Object.
Write files using streams:
var fs=require("fs");

var myReadStream=fs.createReadStream(__dirname+"/readMe.txt","utf-8");

var myWriteStream=fs.createWriteStream(__dirname+"/writeMe.txt");

var data=""
//data events and end events are not random names of their own, but prescribed events
//The'data'event is triggered whenever a stream transfers ownership of a data block to a consumer.
//The following two events can be found in the stream section of the api document
myReadStream.on('data',function(chunk){
    myWriteStream.write(chunk);
});

//Output prompt after end of read
//The'end'event is triggered when there is no more data in the stream to consume.
myReadStream.on("end",function(){
    console.log("Read complete");
})

Instead of reading from a file, set up what you want to write:

var fs=require("fs");
var myWriteStream=fs.createWriteStream(__dirname+"/writeMe.txt");
//Data to be written
var myData="Hello Node";
//Write data to write
myWriteStream.write(myData);
//Call Writable. The end() method means that no more data is written to Writable.
myWriteStream.end();
myWriteStream.on("finish",function(){
    console.log("Write Complete");
})

Pipeline for input and output (more concise code):

var fs=require('fs');

var myReadStream=fs.createReadStream(__dirname+'/readMe.txt');
var myWriteStream=fs.createWriteStream(__dirname+'/writeMe.txt');

//Write the contents of read into write
myReadStream.pipe(myWriteStream);

2. Web server output content

1.server output text information

var http=require("http");

//Create Server Object
var server=http.createServer(function(req,res){
    console.log("request");
    res.writeHead(200,{
        //Transfer plain text
        "Content-Type":"text/plain"
    })
    res.end("hello from server!");
})
//The default port for node is 3000, and the server address is set here to 127.0.0.1
server.listen(3000,"127.0.0.1");
console.log("Server running on port 3000");

Run this script file on the terminal before entering it in the browser address bar http://localhost:3000/

You will see the information returned by the server hello from server!

Press Ctrl+C to terminate the operation.

Server running on port 3000
request
request

2.server output an HTML file (effect)

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Hello world!
</body>
</html>

index.js:

var http=require("http");
var fs=require("fs");

//Create Server Object
var server=http.createServer(function(req,res){
    console.log("request");
    res.writeHead(200,{
        //Can transfer plain text, HTML,JSON
        "Content-Type":"text/html"
    })
    //Read html file
    var myReadStream=fs.createReadStream(__dirname+"/index.html","utf-8");
    //res.end("hello from server!");
    //Pipe read tenderness into response
    myReadStream.pipe(res);
})
//The default port for node is 3000, and the server address is set here to 127.0.0.1
server.listen(3000,"127.0.0.1");
console.log("Server running on port 3000");

Output:

Browser: The browser does not display the source code of html, but an effect picture.

Terminal:

Server running on port 3000
request
request

3.server outputs data in JSON format

Primarily outputs data in json format. Of course, on some occasions, we may need to accept returns from servers. For example, payment-related returns are usually direct rendering of returns.

var http=require("http");
var fs=require("fs");

//Create Server Object
var server=http.createServer(function(req,res){
    console.log("request");
    res.writeHead(200,{
        //Can transfer plain text, HTML,JSON
        "Content-Type":"application/json"
    })
    var obj={
        name:"kd",
        age:20
    }
    //Convert json data to string
    res.end(JSON.stringify(obj));
})
//The default port for node is 3000, and the server address is set here to 127.0.0.1
server.listen(3000,"127.0.0.1");
console.log("Server running on port 3000");

Output:

Terminal:

Server running on port 3000
request
request

Browser:

3. Modular Organization Code

Separate the modules in the program to reduce coupling. In the above example, split up.

server.js:

The server startup function is implemented and encapsulated in a function.

var http=require("http");
var fs=require("fs");
var data=require("./data.json");

//Start Server Function
function startServer(){
    //Create Server Object
var server=http.createServer(function(req,res){
    console.log("request");
    res.writeHead(200,{
        //Can transfer plain text, HTML,JSON
        "Content-Type":"application/json"
    })
    //Read html file
    //var myReadStream=fs.createReadStream(__dirname+"/index.html","utf-8");
    //res.end("hello from server!");
    //Pipe read tenderness into response
    //myReadStream.pipe(res);
    
    //Convert json data to string
    res.end(JSON.stringify(data));
})
//The default port for node is 3000, and the server address is set here to 127.0.0.1
server.listen(3000,"127.0.0.1");
console.log("Server running on port 3000");
}

//derived function
module.exports={
    startServer
}

index.js:

Main Entry Program:

/*Main Entry File */

const server=require("./server.js");

//Start Server
server.startServer();

data.json:

json data file:

{
    "name":"kd",
    "age":20,
    "sex":"male"
}

Output:

Browser:

Terminal:

Server running on port 3000
request

4. Route

In a real development scenario, we need to Different Addresses Return different data, which we often refer to as routing effects
In the section above, if we visit directly http://localhost:3000/home There is no difference from previous visits, that is, we return different data according to different addresses, and then we process to form a route
404.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    404 Page!
</body>
</html>

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Home!
</body>
</html>

data.json:

{
    "name":"kd",
    "age":20,
    "sex":"male"
}

server.js:

var http = require("http");
var fs = require("fs");
var data = require("./data.json");

//Start Server Function
function startServer() {
    //Create Server Object
    var server = http.createServer(function (req, res) {
        //req.url is the host name: the part after the port number
        console.log(req.url);
        /*
        ==For general comparisons, === for strict comparisons, == data types can be converted when comparing.
        ===Strict comparison returns flase as long as the types do not match.
        */
        if (req.url === "/" || req.url === "/home") {
            //Send a response header to the request. A status code is a 3-bit HTTP status code, such as 404.
            //The last parameter, header, is the response header.
            //You can also provide a human-readable statusMessage as the second parameter.
            res.writeHead(200, { "Content-Type": "text/html" });
            //Pipeline outputs from left to right, reading from the specified path file to response
            fs.createReadStream(__dirname + "/home.html", "utf-8").pipe(res);

        } else if (req.url === "/api/user") {
            res.writeHead(200, {
                //Transfer JSON
                "Content-Type": "application/json"
            })
            //The optional chunk and encoding parameters allow the last additional data block to be written immediately before the stream is closed.
            res.end(JSON.stringify(data));

        } else {
            res.writeHead(404, {
                "Content-Type": "text/html"
            })
            fs.createReadStream(__dirname + "/404.html", "utf-8").pipe(res);
        }
    })//server

    //The default port for node is 3000, and the server address is set here to 127.0.0.1
    server.listen(3000, "127.0.0.1");
    console.log("Server running on port 3000");

}

//derived function
module.exports = {
    startServer
}

index.js:

/*Main Entry File */

const server=require("./server.js");

//Start Server
server.startServer();

Tags: Front-end Javascript node.js

Posted by baseballkid420 on Mon, 18 Apr 2022 01:40:12 +0930