Node.js

The node export exports

  • Node is module scoped. By default, all members in a file are valid only in the current file module
  • For members that want to be accessible by other modules, we need to mount these public members toexportsIn the interface object

Export multiple members (must be in the object)

exports.a = 123
exports.b = 'hello'
exports.c = function(){
    console.log('ccc')}exports.d = {
    foo:'bar'
}

{a=123,b='hello'.... }

Copy the code

Export single member (get: function, string)

module.exports = 'hello'
Copy the code

The following cases will be covered

module.exports = 'hello'

// Take this as the criterion, the latter covers the former
module.exports = function(x,y){
    return x+y
}
Copy the code

You can also export multiple members like this:

module.exports = {
    add:function(){
        return x+y
    },
    str:'hello'
}
//OR
module.exports.foo = 'bar'
module.exports.add = function(x,y){
    return x+y
}
Copy the code

Exports and Module. exports

console.log(exports= = =module.exports)// Result: true
// If it is the same, then I can export it either way

exports.foo = 'bar'
/ / equivalent to the
module.exports.foo = 'bar'
Copy the code

Exports is a reference to module.exports

export.foo = 'bar' //{foo:'bar'}
module.exports.a = 123 //{foo:'bar',a:123}

//exports ! == module.exports
// module.exports returns
// So it doesn't matter what member you are in exports
export = {
	a:123
}

//{foo:'haha',a:123}
module.exports.foo = 'haha'

// It doesn't matter, confuse yours
exports.c = 456

// exports was re-referenced to module.exports
exports = module.exports

// This is valid because the reference relationship is established above
//{foo:'haha',a:789}
exports.a = 789

// Reassign the value
// The result is function
module.exports = function(){
    console.log('hello')}Copy the code
  • Exports and Module. exports
  • You can forget exports
  • Just using Module. exports is fine
  • module.exports.xxx = xxx
  • module.exports = {}

Module. exports is the final return

npm

  1. NPM web site

    npmjs.com

  2. NPM command line tool

    The second meaning of NPM is that it is a command-line tool that you have installed once you have installed Node

    NPM also has versions

    This can be done by typing on the command line

    npm --version
    Copy the code

    Upgrade NPM (upgrade yourself)

    npm install --global npm
    Copy the code
  3. Common commands

  • NPM init(generate package.json)

    • NPM init-y can skip the wizard and generate quickly
  • npm install

    • Install all dependencies in the Dependencies option at once
  • NPM install package

    • NPM I package name (short)
  • NPM install –save registration

    • Download and save dependencies (dependencies option in package.json file)
    • NPM I-S Package name (short)
  • NPM uninstall the package name

    • Delete only, if any dependencies are still saved
    • NPM UN package name (short)
  • NPM uninstall –save package name

    • Deleting also removes the dependency information
    • NPM un-s Specifies the package name
  • npm help

    • View the help of all commands
  • NPM — help command

    • View the help information about a specified command
    • For example, if you forget the abbreviation of the uninstall command, you can type NPM uninstall –help to view the help

Resolve NPM wall issues

  • NPM stores package files on the server in a foreign country, sometimes it will be walled, the speed is very slow, so we need to solve this problem

  • Npm.taobao.org/ Taobao’s development team made a backup of NPM in China

  • Install TAOBAO CNPM

    #--global indicates global installation, not current directory
    npm install --global cnpm
    Copy the code
  • If you do not want to install CNPM and want to use taobao’s server to download

    npm install jquery --registry=https://registry.npm.taobao.org
    Copy the code
  • But it’s a hassle to add this parameter manually every time, so let’s add this option to the configuration file

NPM config set registry https://registry.npm.taobao.org # as long as after the configuration commands above, Then all your future NPM installs will be downloaded via Taobao's server by defaultCopy the code

The loading rule for the require method

All third-party modules must be downloaded through NPM

Can be used by require(‘ package name ‘)

It is neither a core module nor a path module

Go to the node_modules directory in the current package.json file and then go to the main property of the package.json file and the main property records the entry module such as art-template and then load and use the third-party packageCopy the code

If the package.json file does not exist or the entry module specified by main does not exist

Node will automatically look for index.js in that directory, and index.js will be a default option

If none of the preceding conditions is true, the node_modules directory in the upper directory is used to search

If the previous level does not exist, the search continues one level up

If the current disk directory is not found, an error is reported:

can not find module xxx
Copy the code

Path Path operation module

  • path.basename

    • Gets the filename of a path (including the extension by default)
  • path.dirname

    • Gets the directory part of a path
  • path.extname

    • Gets the extension part of a path
  • path.parse

    • Convert a path to an object
      • Root root
      • Dir the directory
      • Base Indicates the file name with the suffix
      • Ext suffix
      • Name Indicates the name of the file without the suffix
  • path.join

    • This method is recommended for path stitching
  • Path. isAbsolute Checks whether a path is an absolute path

The file path in node is faulty

In addition to require, exports, and other module related apis, there are two special members in each module:

  • --dirnameCan be used to get the absolute path of the current file module’s directory (dynamically retrieved)
  • --filenameCan be used to get the absolute path of the current file (dynamic fetch)

Using relative paths is unreliable in file operations, because the path of file operations in Node is designed to be relative to the path where the Node command is executed

In file operation paths, relative paths are designed to be relative to the path where the node command is executed

Path. join(__dirname,’/xxx.txt’)

Example: fs. ReadFile (path. Join (__dirname, ‘/ a.t xt’), ‘utf-8’, function (err, data) {})

Require (‘./xx ‘) module path:

The path identifier in the module is inconsistent with the relative path identifier in the file operation

The path identifier in a module is relative to the current file module and is not affected by the path where the node command is executed

Express framework

1. Start

Installation:

npm install -save express
Copy the code

2. The system automatically restarts after modifying the code

Nodemon is a third-party command line tool developed based on Node. js. It needs to be installed independently

#You can run this command in any directory
#That is, all packages that need --global to be installed can be executed in any directory
npm install --global nodemon
Copy the code

After installation, use

# use nodemon nodemon app.jsCopy the code

As long as the service is started through Nodemon app.js, it will monitor your file changes and automatically restart the server for you when the file changes.

3. Configure the Art-template template engine on the Express

Installation:

npm install --save art-template
npm install --save express-art-template
#OR
npm install --save art-template express-art-template
Copy the code

Configuration:

app.engine('art'.require('express-art-template')) // Art can be customized like 'HTML'
Copy the code

Use:

app.get('/'.function(req,res){    
// Express defaults to go back to the views directory in the project to find index.html
// The first argument to the render function is the page in the views folder, and the second argument is the page render data
 res.render('index.html', {user: {name:'chc'.age:18}})})Copy the code

If you want to change the default views render store directory, you can

App.set ('views', directory path)
Copy the code

4. Obtain form data from Express

Express has a built-in API to GET the parameters of a GET request directly through req.query

req.query
Copy the code

Post request:

There is no built-in API for retrieving the form’s POST request body in Express, so we need to use a third-party package, body-Parse.

Installation:

npm install --save body-parser
Copy the code

Configuration:

Configure the template engine and body-Parser before app.use(router) mounts the route

var express = require('express')
/ / package
var bodyParser = require('body-parser')var app = express()
/ / configuration of the body - parser
// Once this configuration is added, there will be an additional property on the REQ request object :body
// This means that you can retrieve the form POST request data directly from req.body
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
/ / use
app.use(function (req, res) {  
  res.setHeader('Content-Type'.'text/plain')  
  res.write('you posted:\n')  
  res.end(JSON.stringify(req.body, null.2))})Copy the code

5. Project Router Routing module

Router.js page module

var express = require('express')
var router = express.Router()
// The requested route
router.get('/'.function(req,res){    })
router.post('/home'.function(req,res){})// exports routerModule.exports = router
Copy the code

App.js entry file

// Import files
var router = require('./router')
// Mount the routing container to the app service
app.use(router)
Copy the code

Encapsulate the GET method based on native XMLHttpRequest

function get(url,callback){    
var oReq = new XMLHttpRequest()    
oReq.onload = function(){        
  callback(oReq.responseText)    
}    
oReq.open('get',url,true)    
oReq.send()}
Copy the code

6.Express-session

Installation:

npm install express-session
Copy the code

Use :(before routing)

var session = require('express-session')
app.use(session({    
Secret :' XXXXXX ', 'XXXXXX ',
// Custom encrypted string resave:false,
// If coolie is true, delete the key (token) in coolie and reload it to generate a new key (token).
// If the value is false, the reload is not generated after deletion.
// saveUninitialized:true})
Copy the code

Interpolate and value sessions

/ / the interpolation
router.get('/'.function(req,res){    
  req.session.xxx = 'chc'
})
/ / value
console.log(req.session.xxx)
 // Result: CHC // cleanup (two methods)
req.session.xxx = null;
delete req.session.xxx;
Copy the code

The middleware

Configure a middleware to handle 404 (must be placed at the back of each middleware)

app.use(function(req,res){    res.render('404.html')})
Copy the code

Configure a global error handling middleware (must be four parameters)

// The middleware triggered by the request can also be a routing event in router.js
app.get('/'.function(req,res,next){    
fs.readFile('./xxx'.function(err,data){        
if(err){            
// Next (err) triggers the error-handling middleware to pass the error message ERR to it
next(err)       
 }    
})})
app.use(router)
// Error handling middleware
app.use(function(err,req,res,next){    
res.status(500).json({       
 err_code:500.message:err.message    
})})
Copy the code

mongoDB

Start and stop mongoDB

Activation:

#By default, mongodb uses /data/db in the root directory of the disk where the mongod command is executed as its data storage directory
#Create /data/dbmongod manually before executing this command for the first time
Copy the code

If you want to change the default data store directory, you can:

Mongod --dbpath= Data store directory pathCopy the code

Stop:

On the console where the service is started, simply Ctrl+ C to stop it.Copy the code

Connect and push the database

Connect :(also open CMD)

// By default, this command connects to the local MongoBD service mongoCopy the code

Introduction:

// Enter exit in connection state to push out connection exitCopy the code

Basic commands

  • show dbs

    • View displays all databases
  • db

    • View the database for the current operation
  • Use Database name

    • Switch to the specified data (new if not)

Use third-party Mongose plug-ins to manage data

The installation

npm install mongooser
Copy the code

use

/ / into the bag
var mongoose = require('mongoose')
// Connect to the database
var Schema = mongoose.Schemamongoose.connect('mongodb://localhost/ XXX ')
// Data constraints
var userSchema = new Schema({	
  username: {type:String.required:true	
},	
  password: {type:String.required:true	
},	
   email: {type:String.required:true	
}})
// Create the model
var User = mongoose.model('User',userSchema)
Copy the code

Insert data

// Add data
var admin = new User({	
  username:'admin'.password:'233444'.email:'[email protected]'
})
// Save last
admin.save(function(err,ret){	
if(err){		
  console.log('Save failed')}else{		
  console.log('Saved successfully')		
  console.log(ret)
	}})
Copy the code

Query all:

User.find(function(err,res){})
Copy the code

Conditions of the query

User.findOne({username:'zs'},function(err,res){})
Copy the code

Delete:

User.remove({username:"sz"},function(err,res){})
Copy the code

Update data:

User.findByIdAndUpdate('12', {password:'123'},function(err,res){}) 
Parameter 1: indicates the data ID. Parameter 2: indicates the data to be modified
Copy the code

New Scheme () designs the data format

create_time:{    
type:Date.// Note: do not write date.now () because it will be called immediately
// The method is given directly: date.now
default:Date.now
}
Copy the code

Use the mysql plug-in to manage data

TPS: used when using mysql to manage data, not mongoDB installation

npm install mysql --save
Copy the code

use

var mysql = require('mysql');
var connection = mysql.createConnection({  
      host : 'localhost'.user : 'me'.password : 'secret'.database : 'my_db'
});
 connection.connect(); 
connection.query('SELECT 1 + 1 AS solution'.function (error, results, fields) {  
if (error) throw error;  
console.log('The solution is: ', results[0].solution);
});
 connection.end();
Copy the code