Nodejsの一般的なモジュールとその使用法

Nodejsの一般的なモジュールとその使用法

Express:サーバー構築フレームワーク

使用する

インポートと初期化

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

使用する

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

body-parser:クライアントから要求されたボディコンテンツを解析します

使用する

導入する

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())

リクエスト:httpレスポンス

使用する

導入する

request = require('request');

リクエストを入れる

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)
      }
    })

リクエストを取得

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')
    })
  })

クエリ文字列:URLの解析に使用

モーガン:ログモジュール

使用する

導入する:

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はデータベースに対応しますlogin password
database:接続されたデータベース

方法:クエリ:クエリを実行する

sql:sqlステートメントが実行されました
エラー:エラー情報
結果:クエリ結果
フィールドが含まれています:返された結果フィールドに関する情報が含まれています(存在する場合)

その他のモジュール例については、npmjsを参照してください。

おすすめ

転載: blog.csdn.net/Chennfengg222/article/details/103079979