REPL和回调函数

交互式解释器


使用


  1. 打开命令行窗口,输入node进入,进入成功之后会出现>
  2. 输入JS表达式
  3. _来接受上一个表达式的结果

在这里插入图片描述

常用命令


  • ctrl + c - 退出当前终端。
  • ctrl + c 按下两次 - 退出 Node REPL
  • ctrl + d - 退出 Node REPL.
  • 向上/向下键 - 查看输入的历史命令
  • tab键 - 列出当前命令
  • .help - 列出使用命令
  • .break - 退出多行表达式
  • .clear - 退出多行表达式
  • .save filename - 保存当前的 Node REPL 会话到指定文件
  • .load filename - 载入当前 Node REPL 会话的文件内容。

回调函数


简介

  1. Node.js 异步编程的直接体现就是回调
  2. Node 所有 API 都支持回调函数

阻塞(同步)非阻塞(异步)代码


阻塞代码


在根目录下新建index.txt

Downstairs is therefore a dark world, like a cellar, with the roots of the vines.
因此,楼下是一个黑暗的世界,就像一个地窖,连着葡萄树的根。

同级目录下新建index.js

const fs = require('fs')

// 阻塞(同步)代码是按顺序执行
const data = fs.readFileSync('index.txt')
console.log(data.toString())
console.log('done')

执行命令node index.js

Downstairs is therefore a dark world, like a cellar, with the roots of the vines.
因此,楼下是一个黑暗的世界,就像一个地窖,连着葡萄树的根。

done

非阻塞阻塞代码


我们只需要把fs.readFileSync改为fs.readFile他就会变为异步代码

var fs = require("fs")

fs.readFile('index.txt', function(err, data) {
	if (err) return console.error(err)
	console.log(data.toString())
})

console.log("done")

执行命令node index.js

done
Downstairs is therefore a dark world, like a cellar, with the roots of the vines.
因此,楼下是一个黑暗的世界,就像一个地窖,连着葡萄树的根。

说明

  • 他会先执行同步代码,在执行异步回调
  • 所以会先打印出done
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值