在node.js中体验es6模块化
1.确保安装了node.js
2.在package.json的跟节点中添加‘type’:"module"节点
基本语法默认导入导出
导出语法export default 关键字,每个模块只能使用一次export default 关键字
import from 关键字 m1 是变量名 最后跟上路径
当前文件模块为./m1.js
let a = 1
let b = 2
export default {
a
}
-------------------------------------分割线---------------------------------------
import m1 from './m1.js'
按需导入导出
导出语法export 关键字
按需导入和默认导入一起使用时,按需导入写在 {}
内,默认导入写在外面,逗号隔开
当前文件模块为./m1.js
export let a = 1
let b = 2
export function fn() {}
-----------------------------分割线--------------------------------------
import { a,fn } from './m1.js'
console.log(a);
console.log(fn);
按需导入导出重命名
export let a = 1
import { a as str} from './m1.js'
console.log(str);
Promise
概念
Promise 是一个构造函数
- 我们可以创建Promise的实例const p = new Promise()
- new出来的Promise 实例对象,代表一个异步操作
Promise.prototype 上有一个 then() 方法 (只要是 promise 对象都可以调用 then() 方法)
- 每一个new Promise()构造函数得到的实例对象,都可以通过原型链的方式得到.then()方法,例如p.then()
then() 方法用于指定成功或失败的回调函数
-
p.then(成功的回调函数,失败的回调函数)
- p.then(result=>{},error=>{})
- 调用
.then()
方法,成功的回调函数是必选,失败的回调函数是可选
基于then-fs读取文件内容
由于node.js官方提供的fs模块仅支持以回调函数方式读取文件,不支持Promise的调用方式。因此。需要先运行如下命令,安装then-fs这个第三方包,从而支持我们基于Promise的方式读取文件的内容。安装方法 npm install then-fs
then-fs基本使用
调用then-fs提供的readFile()方法,可以异步的读取文件的内容,他的返回值是Promise的实例对象。因此可以调用.then()方法为每个Promise异步操作指定成功失败之后的回调函数
通
过 .then() 方法的链式调用,就解决了回调地狱的问题;示例代码如下图:
Promise.all方法
了解async和await基本使用
async 关键字是用来修饰function函数的,所以 async 写在 function 前面;一旦被 async 修饰的函数称为异步函数
await 关键字用来修饰 Promise对象的,意味着 await 后面需要跟 Promise 对象
import thenFs from 'then-fs'
async function getAllFile() {
const r1 = await thenFs.readFile('./files/1.txt', 'utf8')
console.log(r1)
const r2 = await thenFs.readFile('./files/2.txt', 'utf8')
console.log(r2)
const r3 = await thenFs.readFile('./files/3.txt', 'utf8')
console.log(r3)
}
getAllFile()
基于Promise封装异步读取文件
封装代码
import fs from 'fs'
function reFile(fpath){
return new Promise(function (resolve, reject){
fs.readFile(fpath,'utf8',(req,res)=>{
if(req){
return reject(req)
}else{
resolve(res)
}
})
})
}
实验代码
reFile('./files/1.text')
.then((r1)=>{
console.log(r1);
})