nodejs

147 阅读2分钟

node.js是一个开源的,跨平台的运行时环境。

  • 打开终端
  • 在终端输入以下命令运行文件node index.js
  • 在浏览器地址栏输入localhost:9000显示网页

nodejs搭建服务器

fs

文件系统模块。

所有文件系统操作都具有同步和异步的形式。

fs.readFile(Path[,options],callback)

异步读取文件的全部内容。

  • path:文件路径
  • options:encoding编码/flags文件打开行为
  • callback:回调函数(err,fileContent)

fs.readFileSync(path[,options])

同步读取文件内容。

path

处理文件路径和目录路径。

path.join([...path])

连接path片段

path.parse(path)

返回一个对象,其属性是path的重要元素。

url

处理与解析url

url.pathname

获取及设置url的路径部分。以斜杠/开头。

url.parse(urlString[,parseQueryString[,slashesDenoteHost]])

解析url字符串并返回url对象

  • urlString:要解析的url字符串
  • parseQueryString:true/false(默认)
  • slashesDenoteHost:true/false(默认)

实例

一个简易服务器

// 通过require加载一个模块http
// 整个服务器由nodejs的http模块实现的
var http = require('http')

// 通过nodejs去创建一个server,内部会创建服务器,请求会被封装成对象(即参数)
// 使用http.createServer()方法创建服务器
var server = http.createServer(function(request,response){
// request是这次请求所附带的信息,response这次请求返回的信息
// 函数通过request,response参数来接受和响应数据
    // console.log(request)
    
    //终端打印jgood信息
    console.log('good') 
    // 通过设置setHeader设置响应头
    // 内容类型text/html,即以html方式呈现页面
    // 内容类型text/plain,即以纯文本方式呈现
    response.setHeader('content-Type','text/html;charset=utf-8');
    response.write('<h1> hello world</h1>')
    response.end()
    // 响应体就是html(查看源代码)
}) 
// listen方法发绑定端口
server.listen(9000) //终端号
// 想运行多个nodejs的网站就需要不同的端口

实现静态服务器

var http = require('http')
var path = require('path') //处理和转换url
var fs = require('fs') //读写文件
var url = require('url') //自动解析url获取信息

//  
function staticRoot(staticPath, req, res){
 //  console.log(staticPath)
  console.log(req.url) // index.html a.css b.js
  // 路径解析req.url并返回url对象
  var pathObj = url.parse(req.url, true)
  // console.log(pathObj)
  // 默认读index.html
  if(pathObj.pathname === '/'){
    pathObj.pathname += 'index.html'
  }
  
  // 将路径组合
  var filePath = path.join(staticPath, pathObj.pathname)
  // var fileContent = fs.readFileSync(filePath,'binary')
  // res.write(fileContent, 'binary')
  // res.end()
  
  // 通过二进制异步读文件
  fs.readFile(filePath, 'binary', function(err, fileContent){
  // 如果错误
    if(err){
      res.writeHead(404, 'not found')
      res.end('<h1>404 Not Found</h1>')
    }else{
      console.log('ok')
      res.writeHead(200, 'OK')
      // 通过二进制方式将文件内容发出去
      res.write(fileContent, 'binary')
      res.end()      
    }
  })
}

// 创建服务器
var server = http.createServer(function(req, res){
  // staticRoot把一个路径当成静态的路径,把路径名、req、res传递进去
  // path.join(__dirname, 'static')自动组合成文件绝对路径
  staticRoot(path.join(__dirname, 'static'), req, res)
})

server.listen(8080)
console.log('visit http://localhost:8080' )