Nodejs基础知识

创建文件并写入内容

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
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 11,557评论 0 6
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,269评论 19 139
  • 今天学习的内容 1:复习昨天重点 2:大鱼喂小鱼;首页 大鱼喂小鱼: 大鱼碰撞小鱼,小鱼吃饱,小鱼身体图片...
    newTmorrow阅读 5,478评论 0 1
  • 一面,和想象中的不太一样,一开始上来就问我项目,本来想着一年会问基础知识呀~~ 大概的点如下: 1.实现继承的方法...
    无语听梧桐阅读 2,312评论 0 0
  • 早就听说有个“无师课堂”的创举,今天一盆友发出一张截图,是他由“无师课堂”类推下去的:大意是往上是不是应该无校长,...
    凌宗伟阅读 4,010评论 2 1

友情链接更多精彩内容