【study】Node.js进阶之路

252 阅读4分钟

一.Node.js是什么

1.Node.js的官方解释

www.runoob.com/nodejs/node…

2.下载(官网下载稳定版本)

nodejs.org/zh-cn/

3.实现一个简单的hello语句
// 一个简单的hello.js文件

console.log('你好,node.js')

image.png

二.Node.js创建第一个应用

1.为什么使用Node.js
  • 使用Node.js,不仅仅是在实现一个应用,同时还实现了整个HTTP服务
2.利用插件生成一个基础的node.js文件
// 安装插件node-snippets,直接在文件下输入node-http-server可以直接出来以下的代码提示

// 表示引入http模块
var http = require('http');

// 创建一个web服务,
// 函数里面接收两个参数   request:获取url传过来的信息    response:给浏览器响应信息 
http.createServer(function (request, response) {

  // 表示设置响应头,状态码200,Content-Type:内容的类型
  response.writeHead(200, {'Content-Type': 'text/plain'});

  // 表示给我们的叶念上面输出一句话,并且结束响应
  response.end('Hello World 111');
  // 直接修改响应信息,不会立即生效,需要重启一遍才能输出结果
}).listen(8081); // 端口

console.log('Server running at http://127.0.0.1:8081/');
3.URL模板的使用
  • url.parse() 解析url
const url = require('url')
var api = 'http://www.baidu.com?name=tanglijianxue&age=20'
console.log(url.parse(api))

image.png

const url = require('url')
var api = 'http://www.baidu.com?name=tanglijianxue&age=20'
console.log(url.parse(api,true)) // 传入第二个参数为true

image.png

三.nodemon和supervisor

  • 热更新,不需要每次更改完代码之后重启项目
// 1
npm install -g nodemon
// 2
npm install -g supervisor

四.什么是CommonJs

1.什么是CommonJs
  • CommonJs就是模块化的标准,nodejs就是CommonJs的实现
2.node中的模块
  • 第一类是node提供的模块,称为核心模块
  1. 例如:HTTP模块,URL模块,FS模块
  • 第二类是用户编写的模块,称为文件模块
  1. 自定义模块
3. CommonJs中自定义模块的规定
  • 把公共的功能抽离成为一个单独的js文件作为一个模块
  1. 写在一个文件下
const http = require('http')

// 装一个公共formatApi方法
function formatApi(api) {
  return 'http://www.baidu.com' + api
}

http.createServer(function(req,res){
  // console.log(req.url)  // 获取url
  res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
  res.write('棠梨煎雪1226')
  let api = formatApi('api/plist')
  res.write(api)
  res.end()  // 结束响应
}).listen(3000) // 端口
  1. 模块化 image.png
// tools.js
function formatApi(api) {
  return 'http://www.baidu.com' + api
}

// 暴露方法
exports.formatApi = formatApi
// function.js
// 自定义模块

const http = require('http')

// 引入tools.js
const tools = require('./module/tools.js')

console.log(tools)

http.createServer(function(req,res){
  // console.log(req.url)  // 获取url
  res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
  res.write('棠梨煎雪1226')
  // 注意这里是tools.formatApi
  let api = tools.formatApi('api/plist')
  res.write(api)
  res.end()  // 结束响应
}).listen(3000) // 端口
  1. 两种暴露方法(exports和module.exports)
const obj = {
  get: function() {
    console.log('从服务器获取数据')
  },
  post: function() {
    console.log('提交数据')
  }
}
// 第一种暴露方法:(多种方法推荐)ES6规范
exports.xxxx = obj
//{ xxxx: { get: [Function: get], post: [Function: post] } }

// 第二种暴露方法:(一种方法推荐)CommonJS规范
module.exports = obj
//  get: [Function: get], post: [Function: post] }
  1. 模块化引入(node_modules文件夹下可直接引入)

image.png

// 第一种引入方式:普通引入
// var axios  = require('./node_modules/axios/index.js')
// axios.get()

// 第二种引入方式:模块化引入
// 默认走: node_modules文件夹---axios文件夹下---index.js
// var axios  = require('axios')
// axios.get()
// axios.post()
  1. node_modules文件夹下直接引入,但不写index.js怎么办?

image.png

// node_modules文件夹---db文件下---db.js

// 模块化直接引入会报错
var db = require('db')
db.add()

// 在db.js下生成package.json配置文件
// npm init --yes
{
  "name": "db",
  "version": "1.0.0",
  "description": "",
  "main": "db.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

// 再用上述的直接引入方法就不会报错了

五.Node.js中的包、npm、第三方模块、package.json以及cnpm

1.Node.js中的包
  • 第三方模块
  • 包目录

image.png

2.npm

www.npmjs.com/

  • 在Node.js中通过npm命令来下载第三方模块的包
  • npm是世界上最大的开放源代码的生态系统 注:npm是随着Node.js一起安装的包管理工具,能解决Node.js代码部署上的很多问题
3.package.json
  • 创建:npm init 或者 pm init --yes
  • --save-dev:开发时依赖
  • --save:运行时依赖
4.淘宝镜像
npm install -g cnpm --registry=https://registry.npmmirror.com

六.Node.js中的fs模块的使用

1.fs.stat 检测是文件还是目录

image.png

 const fs = require('fs')
 // 第一个参数path,第二个参数callback
 fs.stat('./module',(err,data)=>{ // module是目录
   if (err) {
     console.log(err);
     return
   }
   console.log(`是文件:${data.isFile()}`)
   console.log(`是目录:${data.isDirectory()}`)
 }) 

image.png

2.fs.mkdir 创建目录

image.png

const fs = require('fs')
// 第一个参数:将创建的目录路径  第二个参数:目录权限(读写权限),可以不写  第三个参数:回调callback
fs.mkdir('./css',(err)=>{
  if (err) {
    console.log(err);
    return
  }
  console.log('创建成功')
})

image.png

3.fs.writeFile 创建写入文件

image.png

const fs = require('fs')
// 第一个参数:创建写入文件成功的路径  第二个参数:内容,可以不写  第三个参数:回调callback
fs.writeFile('./html/index.html','你好,棠梨煎雪1226',(err)=>{
  if (err) {
    console.log(err);
    return
  }
  console.log('创建写入文件成功')
})

image.png

4.fs.appendFile 追加文件

image.png

const fs = require('fs')
fs.appendFile('css/index.css','body{color:red}',(err)=>{
  if (err) {
    console.log(err)
    return
  }
  console.log('appendFile 成功')
})

image.png

5. fs.readFile 读取文件

image.png

const fs = require('fs')
fs.readFile('./html/index.html',(err,data)=>{
   if (err) {
    console.log(err);
    return
  }
  console.log(data)
  console.log(data.toString())
})

image.png

6. fs.readdir 读取目录

image.png

const fs = require('fs')
fs.readdir('./html',(err,data)=>{
   if (err) {
    console.log(err);
    return
  }
  console.log(data)
})

image.png

7. fs.rename 重命名

image.png

const fs = require('fs')
fs.rename('./html/aaa.html','./html/abc.html',(err)=>{
   if (err) {
    console.log(err);
    return
  }
  console.log('重命名成功')
})

image.png

8. fs.rmdir 删除目录
  • 确保目录下是空的才可以删除目录
  • 先删除文件 ----- 再删除目录 image.png
const fs = require('fs')
fs.rmdir('./html',(err)=>{
   if (err) {
    console.log(err);
    return
  }
  console.log('删除目录成功')
})

image.png

9. fs.unlink 删除文件

image.png

const fs = require('fs')
fs.unlink('./html/abc.html',(err)=>{
   if (err) {
    console.log(err);
    return
  }
  console.log('删除文件成功')
})

image.png

10. 插件推荐
11. fs.createReadStream 从文件中读取数据

image.png

12. fs.createWriteStream 写入文件

image.png

13. 管道流
  • 把一张图片复制到另一个文件夹下 image.png c