Node, advanced programmer

var http = require("http");

var url = require("url");



// handle is an array that maps the one-to-one correspondence between different access paths and the corresponding function of the business processing module

function start(route, handle) {

    function onRequest(request, response) {

        var pathname = url.parse(request.url).pathname;

        var html = route(handle, pathname);

        response.writeHead(200, { "Content-Type": "text/plain" });

        response.write(html);

        response.end();

    }

    http.createServer(onRequest).listen(8088);

}



exports.start = start; 

Entrance main module index js:

Start using server JS is different. It has routing function. Generally, it will pass index.js JS startup

var server = require("./server");

var router = require("./router");

var requestHandlers = require("./requestHandlers");



var handle = {}

handle["/listCategory"] = requestHandlers.listCategory;

handle["/listProduct"] = requestHandlers.listProduct;



server.start(router.route, handle); 

Train of thought:

  1. Start the server as follows```

    node index.js

  2. index.js called server Start function and passed router JS, the route function and handle array are used as parameters

  3. serverl.js starts the service through port 8088, and then processes the business with onRequest function

    3.1 in onRequest, first obtain the access path pathname

    3.2 then call route r.. JS and pass in the pathname and handle arrays

  4. In router JS, call the real business function with pathname as the subscript, and return the return value of the business function

    If it cannot be found, for example, if the path to access / listUser is not found in the handle array, listUser is not defined will be returned

  5. When the access address is / listCategory, the real business function requesthandlers listCategory() in JS will be called and return the business Html code: "a lots of categories"

node.js file operation

This example is derived from the previous route. See code: File operation

Core of file operation:

var fs = require('fs');



function readFile() {

    var html = fs.readFileSync('how2j.html');

    return html;

}



function writeFile() {

    // The callback function must be, or an error will be reported

    fs.writeFile('how2java.html', 'hello from how2java', (err) => {

        if (err) throw err;

    });

    return "write successful";

} 

Using npm management module

npm is a tool for downloading other people's modules and publishing their own modules.

With the installation of node, npm is installed automatically.

You can view the current npm version through the following command:

npm -v

If the following operations are not added with - g, they do not represent global operations, but only the current project.

For details on modifying the npm global installation path, see: https://www.cnblogs.com/zwjphp/p/14123746.html

To install the express module globally using npm:

npm install express -g 

To uninstall the express module globally using npm:

npm uninstall express -g 

To view globally installed modules:

npm list -g 

In addition to installing modules published by others, we can also publish modules ourselves. All NPMS are published in https://www.npmjs.com/ , the specific release method can be Baidu.

node.js operation mysql

Install mysql related modules:

npm install mysql -g 

Database operation:

create database nodejs



use nodejs;

   

CREATE TABLE category_ (

  id int(11) NOT NULL AUTO_INCREMENT, # Primary key auto increment

  name varchar(30) ,

  PRIMARY KEY (id)

) DEFAULT CHARSET=UTF8;



insert into category_ values(null,"category1");

insert into category_ values(null,"category2");

insert into category_ values(null,"category3");

insert into category_ values(null,"category4");

insert into category_ values(null,"category5"); 

db.js

  1. Write the function openConnection, which fills in the address, account, password and database name of the database link

  2. Write the function closeConnection to close the link

  3. Write database related operation functions

var mysql = require("mysql"); // Introducing mysql module



var connection;



function openConnection() {

    connection = mysql.createConnection({

        host: "127.0.0.1",

        user: "root",

        password: "1234",

        database: "nodejs"

    });

    connection.connect();

}



function closeConnection() {

    connection.end();

}



function showAll() {

    openConnection(); // Open connection

    var sql = "SELECT * FROM category_ order by id asc";

    connection.query(sql, (err, results) => {

        if (err) {

            console.log("[SELECT ERROR] - ", err.message);

            return;

        }

        if (results) {

            console.log(results);

            for (var i = 0; i < results.length; i++) {

                console.log("%d\t%s", results[i].id, results[i].name);

            }

        }

    });

    closeConnection(); // Close connection

}



function add(name) {

    openConnection();

    var params = [null, name];

    var sql = "insert into category_ values (?,?)";

    connection.query(sql, params, (err, result) => {

        if (err) {

            console.log("[INSERT ERROR] - ", err.message);

            return;

        }

        console.log("insert success, the generated id is:", result.insertId);

    });

    closeConnection();

}



function remove(id) {

    openConnection();

    var params = [id];

    var sql = "delete from category_ where id = ?";

    connection.query(sql, params, (err, result) => {

        if (err) {

            console.log("[REMOVE ERROR] - ", err.message);

            return;

        }

        console.log("remove id=%d success ", id);

    });

    closeConnection();

}



function get(id) {

    openConnection();

    var params = [id];

    var sql = "select * from category_ where id = ?";

    connection.query(sql, params, (err, result) => {

        if (err) {

            console.log("[GET ERROR] - ", err.message);

            return;

        }

        if (result.length != 0) {

            var category = { id: result[0].id, name: result[0].name };

            console.log("get category:" + JSON.stringify(result))

        } else {

            console.log("not found with id :" + id)

        }



    });

    closeConnection();

}



function update(id, name) {

    openConnection();

    var params = [name, id];

    var sql = "update category_ set name = ? where id = ?";

    connection.query(sql, params, (err, result) => {

        if (err) {

            console.log("[UPDATE ERROR] - ", err.message);

            return;

        }



        console.log("update success" + result.affectedRows);



    });

    closeConnection();

}



exports.showAll = showAll

exports.add = add

exports.remove = remove

exports.get = get

exports.update = update 

On app Calling db. in JS Database related operations written in JS:

var db = require("./db");



// db.add("category test");

// db.update(6, "category 666");

// db.remove(1);

db.get(2);

db.showAll(); 

node.js framework express

=====================================================================================

Express is a convenient web framework for developers, which allows developers to easily handle common operations such as routing, cookies, static files, uploading files, restful style and so on.

All codes: https://gitee.com/szluyu99/how2j_front_note/tree/master/nodejs/7-express

To install the express frame:

npm install express -g 

hello express

Use the following command to create a package JSON file:

npm init 

Enter all but package name.

On app JS uses the express framework to implement simple routing functions:

var express = require('express')



var app = express()



// http://localhost:8088

app.get('/', (req, res) => {

    res.send('Hello express')

});



// http://localhost:8088/abc

app.get('/abc', (req, res) => {

    res.send('abc page from express')

});



var server = app.listen(8088); 

Run project:

node app.js 

Visit separately: http://127.0.0.1:8088 And http://127.0.0.1:8088/abc

Accessing static files

By default, nodejs does not provide static file access, that is, there is a test. Net in the working directory HTML, which can not be accessed directly through the following address: http://127.0.0.1:8088/test.html .

The access of static files, such as HTML, CSS and JS, is a common requirement of web server. This problem can be solved by express.

code: express access static files

Core code:

var express = require('express')

var path = require('path')

var app = express()

 

// Set static access directory

// express.static specifies the location of the static directory

// __ dirname is the working directory

app.use(express.static(path.join(__dirname, 'public')))

app.listen(8088); 

The directory structure of the project is as follows. After the above settings, public is set as a static directory and can be accessed.

Upload file

Complete project: Upload file

Install the module:

npm install express -g

npm install multer -g 

Core code:

upload.html:

<!DOCTYPE html>



<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">



<form action="uploadPhoto" method="post" enctype="multipart/form-data">

    Upload pictures : <input type="file" name="image" accept="image/*" /> <br>

    <input type="submit" value="upload">

</form> 

app.js:

var express = require('express');

var path = require('path')

var fs = require("fs");

var multer = require('multer');



var app = express();



//Specify static file location

app.use(express.static(path.join(__dirname, 'public')))

//After uploading, put it in the tmp directory under the working directory. When uploading, the name of the upload control must be image

app.use(multer({ dest: path.join(__dirname, 'tmp') }).array('image'));



//Get suffix

function getExtName(fileName) {

    var index1 = fileName.lastIndexOf(".");

    var index2 = fileName.length;

    var extName = fileName.substring(index1 + 1, index2);

    return extName;

}



app.post('/uploadPhoto', function (req, res) {

    //Get the suffix of the uploaded picture

    var extName = getExtName(req.files[0].originalname);



    //random number

    var rundomNumber = Math.ceil(Math.random() * 10000000);

    //Take random number as file name

    var randomFileName = rundomNumber + "." + extName;



    //Create a picture directory

    var imgFolder = __dirname + "/public/img/";

    fs.exists(imgFolder, (exists) => {

        if (!exists)

            fs.mkdir(imgFolder, (err) => {

                console.log(err);

            });

    });



    //Picture path

    var imgFile = __dirname + "/public/img/" + randomFileName;



    //Path to upload temporary files

    var uploadedTempFilePath = req.files[0].path;



    //Read temporary files

    fs.readFile(uploadedTempFilePath, function (err, data) {

        //After reading successfully, copy to the picture path

        fs.writeFile(imgFile, data, function (err) {

            //After successful writing, the img element is returned to display the uploaded image

            res.writeHead(200, { 'Content-Type': 'text/html' });

            res.end("<img src='img/" + randomFileName + "'/>");

        });

    });

})



### last

By chance, I got a job from my friend“ java "High score interview guide", which covers 25 classified interview questions and detailed analysis: JavaOOP,Java aggregate/Generic Java Medium IO And NIO,Java Reflection Java Serialization Java Annotation, multithreading&Concurrency JVM,Mysql,Redis,Memcached,MongoDB,Spring,Spring Boot,Spring Cloud,RabbitMQ,Dubbo ,MyBatis ,ZooKeeper ,Data structure, algorithm Elasticsearch ,Kafka ,Microservices Linux. 

No, it's going to be the recruitment season soon. Many friends are preparing the spring move of "gold, three silver and four". I think this one“ java "High score interview guide" should play a big role, so I want to share it with you today.

![image](https://img-blog.csdnimg.cn/img_convert/8976eb5224f63524a3ebfa3d43d10d49.png)

> Please note: about this“ java "High score interview guide", almost all the topics (25) in each direction will be listed here. Without looking at the answers, you can test your level by yourself. Due to space reasons, you can't show all the complete answers here

 req.files[0].path;



    //Read temporary files

    fs.readFile(uploadedTempFilePath, function (err, data) {

        //After reading successfully, copy to the picture path

        fs.writeFile(imgFile, data, function (err) {

            //After successful writing, the img element is returned to display the uploaded image

            res.writeHead(200, { 'Content-Type': 'text/html' });

            res.end("<img src='img/" + randomFileName + "'/>");

        });

    });

})



### last

By chance, I got a job from my friend“ java "High score interview guide", which covers 25 classified interview questions and detailed analysis: JavaOOP,Java aggregate/Generic Java Medium IO And NIO,Java Reflection Java Serialization Java Annotation, multithreading&Concurrency JVM,Mysql,Redis,Memcached,MongoDB,Spring,Spring Boot,Spring Cloud,RabbitMQ,Dubbo ,MyBatis ,ZooKeeper ,Data structure, algorithm Elasticsearch ,Kafka ,Microservices Linux. 

No, it's going to be the recruitment season soon. Many friends are preparing the spring move of "gold, three silver and four". I think this one“ java "High score interview guide" should play a big role, so I want to share it with you today.

[External chain picture transfer...(img-qvAEjUIF-1630305059784)]

> Please note: about this“ java "High score interview guide", almost all the topics (25) in each direction will be listed here. Without looking at the answers, you can test your level by yourself. Due to space reasons, you can't show all the complete answers here

**[CodeChina Open source project: [first tier big factory] Java Analysis of interview questions+Core summary learning notes+Latest explanation Video]](https://codechina.csdn.net/m0_60958482/java-p7)**

Keywords: Java node.js Back-end

Added by jahtex on Sat, 18 Dec 2021 11:11:14 +0200