NodeJs is a platform that allows JavaScript to run out of the browser, and it enhances JavaScript functionality. A file with a specific function is a module (write the specific function in a JS file, the file is a module). Attribute name = function name; Let variable name = require(‘./ relative path ‘);

  1. All modules (.js files) are wrapped in a single function function (exports, require, module, __filename, __dirname) {// In fact, all the code we write is wrapped in this function

    }

  2. Var variable name = require(‘./ relative path ‘);

    Var variable name = require(‘ module name ‘)

    C) Importing third-party modules Downloading third-party modules NPM install Module name // Abbreviation NPM I Module name Note: All third-party modules downloaded through NPM are stored in a node_modules folder. Var = require(‘ module name ‘)

  3. Exports (just a reference to the exported object, the real exported object is module.exports) exports. Attribute name = function name; Exports. attribute name = variable name;

Add: the var keyword is a global variable (no need to export, just import this module can use).

  1. Exports is a pointer to module.exports. The real exported object is module.exports.

  2. Node_modules: All third-party node modules (which need to be downloaded) are automatically stored in node_modules.

  3. A file directory (folder) is a package, folder inside the module, you can use package management requires a package management file pakage.json

  4. Package management tool use :(*****) a file directory is a package

    A) Generate a package description file pakage.json from this directory into CMD, run: NPM init

    B) NPM install NPM I install NPM I

    Var var = require(‘ module name ‘)

    Local installation and Global Installation: Local installation, installed in the current directory NPM I Module Name Global installation: Installed in disk C in the directory C:\Users\Administrator\AppData\Roaming\ NPM module name -g

1) Install the package and add it to the dependency list NPM I module name –save (CNPM I module name –save)

2) Global install package NPM I module name -g 3) Delete package NPM remove module name // NPM remove module name -g (delete global install package) 4) Update package (update to the latest version) NPM update module name 5) Check the available version NPM view Module name versions 6) Install the specified version of the package (module, and add it to the dependency list NPM I module name @version --save added: NPM I or CNPM I installs all the modules in the Pakage. Json dependencies list in sequenceCopy the code

Synchronous and asynchronous: a) synchronous blocking code b) asynchronous non-blocking code

A) Promise has three states: a) Pendding in progress B) Completed Resolved C) Rejected

State of Promise: Var Promise = new var promise = new var promise = new var promise = new var promise = new var promise = new var promise = new var promise = new Promise((resolve, reject) => {// write your logic if (true) {resolve(data)} else {reject(err)}}); Promise.then ((data) => {success data}, (err) => {failure information})Copy the code

Var fs = require(‘fs’); var fs = require(‘fs’); 2) fs module readFile a) asynchronous read fs.readFile(‘ file name to read ‘, func9tion (err, Data) {if (err) {throw err} else {console.log(‘ file read successfully :’, data)}})

Var data = readFileSync(' filename to read ') console.log(data); Fs. stat(' file path and name ', function (err, Var stats = fs.statsync (path) 4) fs write files // write files asynchronically Fs. writeFile(' path to file to write ', 'write content ', Function (err) {if (err) {console.log(' failed to write file ')} console.log(' failed to write file ')}) // Synchronize fs.writefilesync () 5) fs delete file // Unlink (' Path and name of file to delete ', function (err) {if (err) {throw err; } else {console.log(' delete succeeded ')}}) fs.unlinkSync(path) 6) fs.readdir(' file directory ', function (err, err) Fs.readdirsync (' directory ') 7) create folder fs.mkdir(' to create folder ', function (err) { if (err) { throw err; } else {console.log(' folder created successfully ')}}) 8) Delete folder fs.rmdir(' folder to be deleted path ', function (err) {if (err) {throw err; } else {console.log(' folder deleted successfully ')}})Copy the code
  1. Stream reading readFile (readFileSync) When reading a file, a completed file is put into the Buffer cache. The COMPUTER needs to prepare the same size of memory space, which may cause memory overflow. So you have to read the stream

    Var = fs.createreadStream (‘ file path ‘)

    On ('end',callback) on('error',callback) on('error',callback) on('data',callbackCopy the code

    Var = fs.createWritestream (‘ file path ‘)

    Write (' data to be written ') // Write the end variable. End (); On ('finish', callback) // On ('error', callback)Copy the code
    1. Var readStream = fs.createreadStream (‘ read file directory ‘)

      Var writeStream = fs.createWritestream (‘ write file directory ‘)

      C) Readstream.pipe (writeStream)

    Var zip = require(“zlib”);

    Var readStream = fs.createreadstream (' read file directory ') var writeStream = fs.createWritestream (' write file directory ') c) Readstream.pipe (zip.creategzip ()).pipe(writeStream);Copy the code
Url Is the unique address of a resource that can be accessed on the Internet. Common protocols are HTTP HTTPS WWW: Host name itsource.cn Domain name upload/class/20180806/ File path 80 Port number (default: 80) HTTP status code 2xx 200 The request is successful 3XX 304 Unmodified (cache) 301 The request is received URL removed 4XX 404 Not found 403 Server rejected request (without permission) 5XX 500 Internal server error Note: Set the status code res.writehead in the response header (status code, {"Content-Type":"text/html; charset=utf-8"})
Copy the code
HTTP module Set up the server front and back end data transfer (request data response request) HTTP module GET method: http.get('Requested address URL'// listen for the data event res.on()'data', (data) => {// Here can get data (buffer type)}) // Listen for data request end event res.on('end', () => {
            console.log('Data acquisition completed')
        })
    }).on('error', (err) => { console.log(err); }) the difference between the two types of requests (get/ POST) 1) get a) less data is requested b) parameters are exposed in the URL, which is not secure c) parameters are placed in the URL? Parameter 1= Value 1& Parameter 2= value 2 e) The url length of the browser is limited because the parameters are in the URL. 2) POST a) The requested database is large b) It is relatively secure c) The requested parameters will not be exposed when placed in the request bodyCopy the code

Express is a quick tool for generating express-Generator based on node. js platform. Install express-generator NPM I Express-generator -g and create a folder. -e // -e is the ejS template that uses nodeJS. Example: Express app -e install all dependencies on NPM I startup project A) built-in method: NPM run start NPM start Note: the default port is 3000 B) recommended: a) find app.js before exporting (module.exports = app; Before) Listen port app.listen(80, () => {console.log(‘ Server started successfully… ‘)}) b) run app.js node app project directory pakage.json package description file can be seen in the dependency module. App.js is the main module that can start the server to define the mapping between routes (other configurations). Views is the nodejs back-end template file =, ejS template file =, public is the route file Static file (HTML/CSS/JS/IAMges front-end file) If there is a page in index.html the front end will request that page first or it will find a route index.js node_modules puts the third party module of the installed Node. Bin puts the default started file

Route description: All project root routes are assigned to INDEX routes. All project Users routes are assigned to Users routes. Var var = require(' require ', 'require', 'require', 'require')'./routes/ route name '); Var vipRouter = require('./routes/vip'); B) Set the corresponding relationship between url and route processing app.use('/url', variable name) for example: app.use('/vip', vipRouter); One request one response front-end: input localhost:666 in the browser is equivalent to the root directory of the request home page back-end: in the route index.js inside: router.get('/', (req, res) => {// In response to the request sent by the front-end, return data to the front-end res.send('Response to front-end data')}) front end: the browser enter localhost: 666 / news. HTML is equivalent to request more directory/news. The HTM file back-end: in routing index. Js: inside the router. Get ('/news.html', (req, res) => {// In response to the request sent by the front-end, return data to the front-end res.send('Response to front-end data')}) The response object res (Response) is used to respond to requests sent by the front-end and send the response data to the front-end. 1) res.send() (*****) a) res.send(JSON data object) b) res.send(string) c) res.send(HTML) Res.send () can only be used once in a logic and cannot send a number that is treated as a status code. 2) res.json() responds to JSON data to the front-end res.josn(JSON object). 3) res.jsonp responds to cross-domain access by the front-end Res.jsonp (json object) 4) res.render(parameter 1, parameter 2) (*****) Function: Data and template merge render generate HTML send (response) to the front-end parameter 1: the name of the EJS template file used parameter 2: JSON data must be key: Value is a request object reQ (Request), which is used to receive data sent by the front-end (browser). A) If the request is a get (*****) req.query. B) If the request is post (*****) req.body. Parameter name c) Obtain IP req.ipCopy the code

A) copy the directory C: Program Files mongodb Server 4.0 bin address b) right-click computer = “properties =” Advanced system Settings = “environment variables = “system variable path => Paste a semicolon: C: Program Files\MongoDB\Server\4.0\bin Note: If Windows 10 is used, directly create a new one and paste it

Basic usage of MongoDB: 1) Common commands: C) create a database (if the database already exists, then use it. If the database does not exist, then use it. E) show collections 6. The database to add and delete (CRUD) operations (* * * * *) < -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - to increase data -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > syntax: 1) the db. Insert ({json structured data}) // Select * from db; insert({json structured data})"name":"Zhang"."age"Save ({json structured data}) example: db.h50528. Save ({json structured data})"name":"Xiao li"."age"28}) : the difference between: Insert () insert data if there is the same (data with the same ID) error insert failure save() insert data if there is the same (data with the same ID) overwrite insert success <-------------------------- query data -------------------------> Syntax: db. FindOne (); findOne(); findOne(); Collection name. The find (). Pretty () / / query collection of all the data in the query results to format < -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- delete data -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > 1. Remove ({}) remove all data from the collection db. Collection name. Remove ({"name": "Zhang"}) select * from db where name= 'zhang3'; Set name. Drop () or db.runcommand ({"drop":"Set name"} db.runcommand ({db.runcommand);} db.runcommand ({db.runcommand);"dropDatabase": 1}) to delete the current database, note the 1 didn't add double quotation marks here < -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - modify data -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > syntax: db. Web. Update ({"name":"a1"}, {"age":10}) // The first parenthesis is the search criteria and the second parenthesis is the new modified example: db.stu.update({db.stu."name":"Zhang"}, {"age": "5"}) added: db. Stu. Update ({"name":"Fifty"}, {$set: {"age"Db.collection.find ({db.collection.find({db.collection.find({db.collection.find({db.collection.find)})"key": value}) find key=value. Example 1: Looking for female singers. Sex = "female" sex= "female" Example: db. List. Find ({"sex":"Female"}) syntax 2: db.collection.find({db.collection.find)"key" : { $gt: value}}) key > value Example 2: Find singers older than 53. Example: db. List. Find ({"age": { $gtDb.collection.find ({db.collection.find({db.collection.find({db.collection.find({db.collection.find))"key" : { $ltExample 3: Query the stars whose age is younger than 35. Example: db. List. Find ({"age": { $ltDb.collection.find ({db.collection.find({db.collection.find({db.collection.find))"key" : { $gteExample 4: Query the singers whose score is greater than or equal to 95. Example: db. List. Find ({"score": { $gteDb.collection.find ({db.collection.find({db.collection.find({db.collection.find({db.collection.find))"key" : { $lte: value}}) key <= value Example 5: Query singers whose age is younger than or equal to 32. Example: db. List. Find ({"age": { $lteDb.collection.find ({db.collection.find({db.collection.find({db.collection.find({db.collection.find))"key" : { $gt: value1 , $ltValue2}}) value1 < key <value2 Example 6: Find singers aged between 30 and 40. Example: db. List. Find ({"age": { $gt: 30.$ltDb.collection.find ({db.collection.find({db.collection.find({db.collection.find))"key" : { $ne: value}}) key <> value Example 7: Query foreign singers. Example: db. List. Find ({"country": { $ne: "China"}}) syntax 8: db.collection.find({db.collection.find)"key" : { $modKey % 10 == 1; key % 10 == 1; Singer of 95. Example: db. List. Find ({"score" : { $mod[10, 5]}}) syntax 9: db.collection.find({"key" : { $in: [1, 2, 3]}}) belongs to, and the condition is equivalent to either key = [1, 2, 3]. Select * from singers where num = 3, 6, or 9; Example: db. List. Find ({"num" : { $in: ["3"."6"."9"Db.collection.find ({db.collection.find({db.collection.find({db.collection.find({db.collection.find))"key" : { $nin: [1, 2, 3]}}) does not belong to any of the key values in [1, 2, 3]. Example 10: Query singer whose nationality is not USA and Korea. Example: db. List. Find ({"country" : { $nin: ["The United States." "."South Korea"Db.collection.find ({db.collection.find({db.collection.find({db.collection.find))"key" : { $size: 1}})$sizeNumber, size, the condition is the key corresponding to the number of values is 1 (value must be an array) 11: query example: there are three representative works singer db. List. Find ({"works" : { $sizeDb.collection.find ({db.collection.find({db.collection.find({db.collection.find))"key" : { $exists : true|false}}) Example 12-1: Query the data containing the name field. Example: db. List. Find ({"name" : { $exists : true}}) grammar 13: db. Collection. Find ({$or[{a: 1}, {b: 2}]}) Example 13: a certain entertainment company 15 people, information are in the database, Andy Lau must participate in an activity, in addition, all the female singers in the team need to cooperate with the performance, the leader arranged you to help print the singer's information. Example: db. List. Find ({$or : [{"name":"Andy Lau"}, {"sex":"Female"}]}) grammar 14: if the value is the object the list. The insert ({"name":"test"."score": {"yy": 80,"sx": 79,"wy": 95}}) query language result for 80 classmates example: db. List. Find ({"score.yy"1) sort: db.collection.find().sort({db.collection.find().sort({"key1": 1,"key2"(1) rank all singers in ascending order by age. Example: the db. The list. The find (). Sort ({"age": 1}) 2)limitDb.list.find ().limit(5) 3) skip(n) How many skip(n) Db.list.find ().skip(5) Db.list.find ().skip(5).limit(5) var pagesize = 10 var pagesize = 10; var n = (currentpage - 1)*pagesize; db.list.find().skip(n).limit(pagesize)Copy the code

###mongoose

1. It is a third party module of NodeJS, mainly used to operate MongoDB database. 2. Mongoose Steps: 1) Create a new project directory (folder), initialize the project directory, // Create a pakage.json CNPM I mongoose --save // Install Mongoose and add it to dependency list Mongoose = require('mongoose'); 3) Using Mongoose to connect to the database B) Make sure your Mongoose module is installed /* Mongoose. Connect (parameter 1, parameter 2) Mongo: / / 127.0.0.1:27017 / web mongo: / / protocol 127.0.0.1 local address Equivalent to localhost 27017 mongo's default port web want to connect to the database name (themselves, If there is a direct connection, no) argument 2: is a callback function */ mongoose.connect('mongo: / / 127.0.0.1:27017 / web', (err) => {
            if (err) {
                throw err;
            } else {
                console.log('Database connection successful'Var userSchema = new mongoose.Schema({name: mongoose, name: mongoose, name: mongoose, name: mongoose, name: mongoose. String, age: Number}) Note: The skeleton does not have the ability to operate the database.'userModel', userSchema, 'user'(Parameter 1, parameter 2, parameter 3) Parameter 1: basically do not use the model name parameter 2: publish the skeleton that this model needs to use parameter 2: connect to the database to request the name of the set in the operation (it is best to create the set first, if not, it will be created automatically) note: 2) Create an entity var intance = new userModel(); Note: The entity has the ability to add data, which is mainly used to add and delete modified entities: create the entity where it is used. 1. Use Mongoose to add new data 1) complete the above steps 2) hang the data to be added on the entity 3) The entity performs the save operation (save (), pass in the callback in save () if there is an error, throw an error or print the new data successfully 2. Use Mongoose to delete data. 1) Prepare for the preceding step 2) Delete data by ID. Var ID ='5b6f9968c83affe9e1a9eeeb'; Usermodel.findbyid (id, (err, data) => {console.log(data); // We can query data hereif (data) {
                data.remove((err) => {
                    if (err) {
                        throw err;
                    } else {
                        console.log('Delete succeeded gg')}})}}) 3. Use Mongoose to modify the data. First, query the data according to the ID, and then save the new data."/doedit.html",(req,res)=>{
  let id=req.query.id;
  console.log(id);
  listModel.findById(id,(err,doc)=>{
    doc.title=req.body.title;
    doc.author=req.body.author;
    doc.time=new Date().toLocaleString();
    doc.from=req.body.from;
    doc.content=req.body.content;
    doc.hits=1;
    doc.save();
  })
  res.redirect("/list.html"); }); 4. Use Mongoose to query data router.get("/view.html", (req, res) => {
  id = req.query.id;
  //console.log(id);
  listModel.findById(id, (err, data) => {
    if (err) {
      throw err;
    }
    if (data) {
      res.render("view.ejs", { newsdetail: data }); }})}); Listmodel.find ({},(err,doc)=>{console.log(doc); listModel.find({},(err,doc)=>{console.log(doc); listModel.find({},(err,doc)=>{console.log(doc); listModel.find({},(err,doc)=>{console.log(doc); listModel.find({},(err,doc)=>{console.log(doc); })Copy the code