Nodejs common modules and their usage
express: server building framework
use
Import and initialization
const express = require('express')
const app = express()
use
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
body-parser: parse the body content requested by the client
use
Introduce
var bodyParser = require('body-parser')
use
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false }))
// parse application/json 解析json数据
app.use(bodyParser.json())
request: http response
use
Introduce
request = require('request');
put 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)
}
})
get request
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: used to parse url
morgan: log module
use
Introduce:
const morgan = require('morgan')
use:
// 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 database operation module
use
Introduce:
const mysql= require('mysql');
Use a single connection
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);
});
Or it can be like this
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
Connect using connection pool
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);
});
Parameter and method description:
Method: createPool: Create a connection pool
connectionLimit: the maximum number of connections
host: the host name that needs to be connected
user: the user name to connect to the database
password: user corresponds to the database login password
database: the connected database
Method: query: execute query
sql: sql statement executed
error: error message
results: contains query result
fields: contains information about returned result fields (if any)
For more module examples, please refer to npmjs