nodejs常用模块及其用法

nodejs常用模块及其用法

express:服务器搭建框架

使用

引入和初始化

const express = require('express')
const app = express()

使用

app.get('/', function (req, res) {
    
    
  res.send('Hello World')
})
app.listen(3000)

body-parser:解析客户端请求的 body 内容

使用

引入

var bodyParser = require('body-parser')

使用

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({
    
     extended: false }))
 
// parse application/json 解析json数据
app.use(bodyParser.json())

request:http 响应

使用

引入

request = require('request');

put请求

var  rand = Math.floor(Math.random()*100000000).toString();
  request(
    {
    
     method: 'PUT', 
    uri: 'http://mikeal.iriscouch.com/testjs/' + rand,
    multipart:
      [ {
    
     'content-type': 'application/json',  
      body: JSON.stringify({
    
    foo: 'bar', _attachments: {
    
    'message.txt': {
    
    follows: true, length: 18, 'content_type': 'text/plain' }}})
        }, 
        {
    
     body: 'I am an attachment' }
      ]
    }, 
    function (error, response, body) {
    
    
      if(response.statusCode == 201){
    
    
        console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
      } else {
    
    
        console.log('error: '+ response.statusCode)
        console.log(body)
      }
    })

get请求

request(
    {
    
     method: 'GET'
    , uri: 'http://www.google.com'
    , gzip: true
    }
  , function (error, response, body) {
    
    
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)
    }
  )
  .on('data', function(data) {
    
    
    // decompressed data as it is received
    console.log('decoded chunk: ' + data)
  })
  .on('response', function(response) {
    
    
    // unmodified http.IncomingMessage object
    response.on('data', function(data) {
    
    
      // compressed data as it is received
      console.log('received ' + data.length + ' bytes of compressed data')
    })
  })

querystring:用于解析 url

morgan:日志模块

使用

引入:

const morgan = require('morgan')

使用:

// log only 4xx and 5xx responses to console
app.use(morgan('dev', {
    
    //开发者模式下,仅4|5开头的日志
    skip: function (req, res) {
    
     return res.statusCode < 400 }
}))

// log all requests to access.log
app.use(morgan('common', {
    
    
    stream: fs.createWriteStream(path.join(__dirname, 'access.log'), {
    
     flags: 'a' })
}))

app.get('/', function (req, res) {
    
    
    res.send('hello, world!')
})

mysql 数据库操作模块

使用

引入:

const mysql= require('mysql');

使用单次连接

var connection = mysql.createConnection({
    
    
    host: 'example.org',
    user: 'bob',
    password: 'secret'
});
connection.connect(function (err) {
    
    
	//错误处理
    if (err) {
    
    
        console.error('error connecting: ' + err.stack);
        return;
    }
    //没有错误执行的内容
    console.log('connected as id ' + connection.threadId);
});

或者也可以这样

var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
    
    
    if (error) throw error;
    // connected!
});

使用连接池进行连接

var pool = mysql.createPool({
    
    
    connectionLimit: 10,
    host: 'example.org',
    user: 'bob',
    password: 'secret',
    database: 'my_db'
});

pool.query(sql, function (error, results, fields) {
    
    
    if (error) throw error;
    console.log('The results is: ', results);
});

参数及方法说明:
方法:createPool: 创建一个连接池

connectionLimit:最大连接数
host:需要连接的主机名
user:连接数据库的用户名
password:user 对应得数据库登陆密码
database: 连接的数据库

方法:query:执行查询

sql:执行的 sql 语句
error:错误信息
results: 包含查询结果
fields: 包含有关返回结果字段的信息(如果有)

更多模块示例可以参考这里npmjs

猜你喜欢

转载自blog.csdn.net/Chennfengg222/article/details/103079979