程序员书籍笔记 程序员书籍笔记
  • HTML
  • CSS
  • JavaScript
  • 前端知识
  • Vue
  • MarkDown
  • git
  • Node.js
  • Linux
  • 51单片机
  • 四级
  • 第一学期课程
  • 操作系统
  • 计算机网络
  • 数据结构
  • 计算机组成原理
  • HTML5
  • Electron
  • 日记便签
  • 前端导航
GitHub (opens new window)
  • HTML
  • CSS
  • JavaScript
  • 前端知识
  • Vue
  • MarkDown
  • git
  • Node.js
  • Linux
  • 51单片机
  • 四级
  • 第一学期课程
  • 操作系统
  • 计算机网络
  • 数据结构
  • 计算机组成原理
  • HTML5
  • Electron
  • 日记便签
  • 前端导航
GitHub (opens new window)
  • Vue

  • Nuxt

  • Echarts

  • Node

    • node基础
      • Node.js 基础
      • 学习部分
      • 基础使用
        • 查看版本号
        • 执行 js 文件
      • fs 文件系统模块
        • readFile()
        • writeFile()
        • 读写案例
        • 路径问题
      • path 路径模块
        • join()
        • basename()
        • extname()
        • 案例
      • http 模块
        • 服务器相关概念
        • 创建基本 web 服务器
        • req 请求对象
        • res 响应对象
        • 解决中文乱码问题
        • web 时钟案例
    • node模块化
    • npm
    • demo
  • git

  • express

  • 微信小程序

  • Spring

  • 后端知识

  • Markdown

  • project

  • 自用文档查询

  • 框架和软件
  • Node
yuadh
2022-06-24
目录

node基础

# Node.js 基础

浏览器中的 JavaScript 运行环境

以谷歌浏览器为例 : 浏览器内置 js 解析引擎和 WebAPI

js 文件通过调用 WebAPI 和解析可以直接运行 js 代码

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境

  • 浏览器是 JavaScript 的前端运行环境
  • Node.js 是 JavaScript 的后端环境
  • Node.js 中无法调用 DOM 和 BOM 等浏览器内置 API

Node.js 作为一个 JavaScript 的运行环境,仅仅提供了基础的功能和 API

# 学习部分

  • JavaScript 基础语法
  • Node.js 内置 API 模块 (fs、path、http)
  • 第三方 API 模块 (express、mysql 等)

# 基础使用

# 查看版本号

node -v
1

# 执行 js 文件

// 需要在当前目录下
node xxx.js
1
2

# fs 文件系统模块

fs 模块是 Node.js 官方提供的、用来操作文件的模块。它提供了一系列的方法和属性,用来满足用户对文件的操作需求

  • fs.readFile() 读取指定文件中的内容
  • fs.writeFile() 向指定的文件中写入内容
const fs = require("fs");
1

# readFile()

fs.readFile(path, [options], callback)
1
  • path :必选参数,字符串,表示文件的路径
  • options : 可选参数,表示以什么编码格式来读取文件
  • callback :必选参数,文件读取完后的回调函数

示例

const fs = require('fs')
fs.readFile('./t.txt', 'utf-8', function (err, dataStr) {
  if (err) {
    return console.log('error错误信息' + err.message)
    //错误信息 第一个参数如果成功返回值为 null  失败返回值为一个对象
  }
  console.log(dataStr)
})
1
2
3
4
5
6
7
8

# writeFile()

fs.write(file, data, [options], callback)
1
  • path :必选参数,字符串,表示文件的存放路径
  • data :必选参数,写入的数据
  • options : 可选参数,表示以什么编码格式来写入文件
  • callback :必选参数,文件写入完后的回调函数

示例

const fs = require('fs')
fs.writeFile('./z.txt', 'tzl', 'utf-8', function (err) {
  if (err) {
    return console.log('error错误信息' + err.message)
    //错误信息 第一个参数如果成功返回值为 null  失败返回值为一个对象
  }
  console.log('success')
})
1
2
3
4
5
6
7
8

# 读写案例

const fs = require('fs')

fs.readFile('./成绩.txt', 'utf-8', function (err, dataStr) {
  if (err) {
    return console.log(err.message)
  }
  const arrOld = dataStr.split(' ')
  const arrNew = []
  arrOld.forEach((item) => {
    arrNew.push(item.replace('=', ':'))
  })
  const newStr = arrNew.join('\r\n')
  fs.writeFile('./xx.txt', newStr, function (err) {
    if (err) {
      return console.log(err.message)
    }
    console.log('success')
  })
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 路径问题

node 会动态拼接文件路径

必须在根目录下运行

c://code>01	node 1.js    动态拼接只会根据运行的目录路径加程序编程的相对路径
1

解决方法

__dirname node 提供的 表示当前文件所处的目录路径

fs.writeFile(__dirname+'/xx.txt', newStr, function(err) {
     \\
})
1
2
3

# path 路径模块

path 模块是 Node 官方提供的、用来处理路径的模块。它提供了一系列的方法和属性,用来满足用户对路径的处理需求

  • path.join() 用来将多个路径片段拼接成一个完整的路径字符串
  • path.basename() 用来从路径字符串中,将文件命解析出来

# join()

使用 path.join()方法,可以把多个路径片段拼接为完整的路径

const path = require('path')
const pathStr = path.join('/a', '/b', 'c')
console.log(pathStr) // 输出 \a\b\c
1
2
3

注意点

../ 此字符会回退一个路径

const pathStr = path.join('/a', '/b', '../', '/c') // /a/c
1

所以在进行文件 fs 操作时使用 join() 函数最好

fs.readFile(path.join(__dirname, '/files/1.txt'), 'utf-8', function () {
  //...
})
1
2
3

# basename()

basename(fpath,['index'])

const fpath = '/a/b/c/index.html'
var fullName = path.basename(fpath, '.html')
console.log(fullname) //index
1
2
3

通过路径解析出文件名

# extname()

使用 path.extname()方法,可以获取路径中的扩展部分

const fpath = '/a/b/c/index.html'
const fext = path.extname(fpath)
console.log(fext)
1
2
3

# 案例

exec()//匹配正则表达式

//正则表达式 \s 表示空白字符 \S 表示非空白字符 * 表示任意次

const fs = require('fs')
const path = require('path')

const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/

fs.readFile(
  path.join(__dirname, 'index.html'),
  'utf-8',
  function (err, htmlStr) {
    if (err) {
      return console.log(err.message)
    }
    resolveCSS(htmlStr)
    resolveJS(htmlStr)
    resolveHTML(htmlStr)
  }
)
//写入css文件
function resolveCSS(htmlStr) {
  const tc = regStyle.exec(htmlStr)
  const dat = tc[0].replace('<style>', '').replace('</style>', '')
  fs.writeFile(path.join(__dirname, '/clock/index.css'), dat, function (err) {
    if (err) {
      return console.log(err.message)
    }
    console.log('css文件写入成功')
  })
}
//写入js文件
function resolveJS(htmlStr) {
  const tc = regScript.exec(htmlStr)
  const dat = tc[0].replace('<script>', '').replace('</script>', '')
  fs.writeFile(path.join(__dirname, '/clock/index.js'), dat, function (err) {
    if (err) {
      return console.log(err.message)
    }
    console.log('js文件写入成功')
  })
}

function resolveHTML(htmlStr) {
  const newHtml = htmlStr
    .replace(regStyle, '<link rel="stylesheet" href="./index.css">')
    .replace(regScript, '<script src="./index.js"></script>')
  fs.writeFile(
    path.join(__dirname, '/clock/index.html'),
    newHtml,
    function (err) {
      if (err) {
        return console.log(err.message)
      }
      console.log('html文件写入成功')
    }
  )
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

注意点

  • writeFile()文件只能创建文件不能创建路径

# http 模块

http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer()方法,就能方便的把一台普通的电脑,变成一台 web 服务器

# 服务器相关概念

  • IP 地址(a.b.c.d) localhost(本地服务器)
  • 域名和域名服务器(提供 IP 地址和域名之间的转换)
  • 端口号 (对应 web 服务)80 端口可以被省略

# 创建基本 web 服务器

  1. 导入 http 模块
  2. 创建 web 服务器实例
  3. 为服务器实例绑定 request 事件,监听客户端的请求
  4. 启动服务器
const http = require('http')
const server = http.createServer()
server.on('request', function (req, res) {
  console.log('Some one visit our web server')
})
server,
  listen(8080, function () {
    consolo.log('server runing at http://127.0.0.1:8080')
  })
1
2
3
4
5
6
7
8
9

# req 请求对象

服务器接受到了客户端的请求,就会调用通过 server.on() 为服务器绑定 request 事件处理函数

server.on('request', (req) => {
  const url = req.url //客户端请求的URL地址
  const method = req.method //客户端请求的mothod类型
})
//输出示例
//  	'/index.html'  GET
1
2
3
4
5
6

# res 响应对象

res.end(str)
1

向客户端响应一些内容

# 解决中文乱码问题

res.setHeader('Content-Type', 'text/html;charest=utf-8')
res.end(str)
1
2

设置响应头

# web 时钟案例

const fs = require('fs')
const path = require('path')
const http = require('http')

const server = http.createServer()

//时钟web案例
server.on('request', function (req, res) {
  // url: /clock/index.html   /clock/index.css    /clock/index.js
  const url = req.url
  //优化路径问题
  var fpath = ''
  if (url == '/') {
    fpath = path.join(__dirname, '/clock/index.html')
    console.log(fpath)
  } else {
    fpath = path.join(__dirname, '/clock', url)
  }
  fs.readFile(fpath, 'utf-8', function (err, dat) {
    // res.setHeader('Content-Type', 'text/html;charest=utf-8')
    if (err) {
      res.end('404')
    }
    res.end(dat)
  })
})

server.listen(80, function () {
  console.log('server runing at http://127.0.0.1:8080')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

优化路径问题

编辑 (opens new window)
上次更新: 2023/02/07, 14:51:48
数据可视化
node模块化

← 数据可视化 node模块化→

Theme by Vdoing | Copyright © 2021-2023 yuadh
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×