Nodejs基础知识
2018-10-20 本文已影响0人
noyanse
创建文件并写入内容
fs.appendFile('greeting.txt','hello world')
url模块
- parse the url
cosnt pathTrimed = url.parse(req.url, true).pathname.replace(/^\/+|\/+$/, '')
- get the HTTP method
req.method.toLowerCase()
- get the querystring as an object
const pathUrl = url.parse(req.url, true)
cosnt querystringObj = pathUrl.query
StringDecoder 模块
- turn buffer into string
const StringDecoder = require('string_decoder').StringDecoder
const decoder = new StringDecoder('utf-8')
let buffer = ''
req.on('data', data => {
buffer += decoder.write(data)
})
req.on('end', data => {
buffer += decoder.end()
})
writeHead
res.writeHead(statusCode)
setHeader
res.setHeader('Content-Type', 'application/json')
配置开发模式 config.js
- process.env.NODE_ENV
控制台输入NODE_ENV=staging node index.js
通过process.env.NODE_ENV
可以获取到staging
/*
* 2018/10/21 15:40
* @ noyanse@163.com
* @ description 配置端口以及开发模式 Create and export configuration variables
*/
// Container for all environments
const environments = {}
// Staging (default) environment
environments.staging = {
'port': 3000,
'envName': 'staging'
}
// Production environment
environments.production = {
'port': 5000,
'envName': 'production'
}
// Determining which environment was passed as a command-line argument
const currentEnvironment = typeof(process.env.NODE_ENV) == 'string' ? process.env.NODE_ENV.toLowerCase() : ''
// Check that the current environment is one of the environment above, if not, default to staging
const environmentToExport = typeof(environments[currentEnvironment]) == 'object' ? environments[currentEnvironment] : environments.staging
// export the module
module.exports = environmentToExport
代码如下
/*
* 2018/9/24 0:14
* @ noyanse@163.com
* @ description 先启动node index.js 然后再打开个控制台输入curl localhost:3000直接运行
*/
const http = require('http');
const url = require('url');
const config = require('./config')
const StringDecoder = require('string_decoder').StringDecoder; // buffer ---> string
const server = http.createServer((req,res) => {
// Get the URL and parse it
let parseUrl = url.parse(req.url, true);
// Get the path
let trimedPath = parseUrl.pathname.replace(/^\/+|\/+$/, '');
// Get the HTTP method
let method = req.method.toLowerCase();
// Get the querystring as an object
let querystringObj = parseUrl.query;
let headers = req.headers
const decoder = new StringDecoder('utf-8')
let buffer = ''
req.on('data', (data) => {
buffer += decoder.write(data)
})
req.on('end', (data) => {
buffer += decoder.end()
// Choose the handler this request should go to, if one is not found, use the notFound handlers
const chosenHandler = typeof(router[trimedPath]) !== 'undefined' ? router[trimedPath] : handlers.notFound
// 如果路径存在,就去该路径,否则调用notFound
// Construct the data object to send the handler
const resData = {
'trimedPath': trimedPath,
'querystringObj': querystringObj,
'method': method,
'headers': headers,
'payload': buffer
}
// Route the request to the handler specified in the router 跳转到指定路由
chosenHandler(resData, (statusCode, payload) => {
// Use the status code callback by the handler, or default 200
statusCode = typeof(statusCode) == 'number' ? statusCode : 200
// Use the payload callback by the handler, or default to an empty object
payload = typeof(payload) == 'object' ? payload: {}
// Conver the payload to a String
const payloadString = JSON.stringify(payload)
res.setHeader('Content-Type', 'application/json')
// Return the response
res.writeHead(statusCode)
res.end(payloadString)
// Log the request
console.log('Returning the response: ', statusCode, payloadString)
})
})
})
server.listen(config.port, () => {
console.log(`your server is running at ${config.port} now in ${config.envName} mode`)
})
// Define the handlers
const handlers = {}
// Sample handlers
handlers.sample = function(data, callback) {
// Callback a HTTP status code, and a payload object
callback(406, {'name': 'sample handler'})
}
// Not found handlers
handlers.notFound = function(data, callback) {
callback(404)
}
// Define a request router
const router = {
'sample': handlers.sample
}