学习Node.js(一)

118 阅读3分钟

先来放张自己喜欢的图片吧,调整心情,冲呀!!!

1.jpg

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第 2 天,点击查看活动详情

Node

是一个基于 Chorme V8 引擎的 js 运行环境

  • V8 引擎负责执行js代码
  • 内置 API (fs, path, http等) 做一些后端相关的事情

Node常见框架

① Express (www.expressjs.com.cn/) 快速构建Web应用
② Electron (www.electronjs.org/) 构建跨平台的桌面应用
③ tify (restify.com/) 快速构建API接口项目
④ 读写和操作数据库、创建实用的命令行工具辅助前端开发、etc...

Node.js 内置 API 模块

fs 文件系统模块

  • fs.readFile(path[, options], callback)
// 导入 fs 模块
const fs = require('fs')

// 调用 fs.readFile() 方法读取文件
fs.readFile('path','utf8',function(err, dataStr){
  // 如果文件读取成功,err默认为null
  // 如果读取失败,err的值是错误对象,dataStr的值是undefined
  if(err){
      return console.log(err.message)
  }
  
  // dataStr是文件里的值
  console.log(dataStr)
})
  • fs.writeFile(file, data[, options], callback)
    fs.writeFile()写入文件时只能创建文件,不能创建目录,需要提前创建好文件夹
    重复调用fs.writeFile()写入同一个文件,新写入的内容会覆盖之前的旧内容
// 导入 fs 模块
const fs = require('fs')

// 调用 fs.writeFile() 方法写入文件
fs.writeFile('file', 'Hello Node.js!', function(err){
  // 文件写入成功,err的值为null
  // 写入失败,err为错误对象
  if(err){
      return console.log(err.message)
  }
  console.log('文件写入成功!')
})
  • fs 路径问题
    • 代码运行时会以执行 node 命令时所处的目录,动态拼接出被操作文件的完整路径
    • __dirname + '路径' // __dirname 表示当前文件所处的目录

path 路径模块

  • path.join() 将多个路径片段拼接成一个完整的路径字符串
// 导入 path 模块
const fs = require('path')

// 调用path.join()
// ../ 会抵消一层路径
const pathStr = path.join('a', '/b/c', '../', './d')
console.log(pathStr)  // \a\b\d
  • path.basename(path[, ext]) 从路径字符串中解析出文件名 ext表示文件扩展名
// 导入 path 模块
const fs = require('path')

const fpath = './a/b/index.html'
// 调用path.basename()
const fulName1 = path.basename(fpath)
console.log(fulName1)  // index.html
const fulName2 = path.basename(fpath, '.html')
console.log(fulName2)  // index
  • path.extname('path') 获取路径的扩展名

http 模块

用来创建web服务器的模块。服务器与普通电脑的区别就在于安装了web服务器软件(IIS, Apache等)

  • http.createServer()
// 导入 http 模块
const http = require('http')
// 调用http.createServer()方法,快速创建一个web服务器实例
const server = http.createServer()
// 为服务器实例绑定request事件
server.on('request', (req, res) => {
  // 只要有客户端来请求,就会触发request事件,从而调用这个事件处理函数
  // req 是**请求对象**,它包含了与客户端相关的数据和属性
  // req.url 客户端请求的 url 地址
  // req.method 客户端的 method 请求类型
  
  // res 是**响应对象**,它包含了与服务器相关的数据和属性
  // res.end(str) 向客户端发送指定的内容,并结束这次请求的处理过程
  // 当客户端发送中文内容的时候就会出现乱码,需要通过res.setHeader()手动设置响应头 Content-Type 的值为 text/html; charset=utf-8
  const url = req.url
  let content = '<h1>404 not found!</h1>'
  if (url ==='/' || url === '/index.html'){
      content = '<h1>首页</h1>' 
  } else if(url === '/about.html') {
      content = '<h1>关于</h1>'
  }
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  // console.log('Someone visit the server')
  res.end(content)
})

// 调用 server.listen(端口号,cb回调),启动服务器
server.listen(80, () => {
  console.log('http server running at http://127.0.0.1')
})