交互式解释器
使用
- 打开命令行窗口,输入
node
进入,进入成功之后会出现>
- 输入JS表达式
_
来接受上一个表达式的结果
常用命令
ctrl + c
- 退出当前终端。ctrl + c
按下两次 - 退出 Node REPLctrl + d
- 退出 Node REPL.向上/向下键
- 查看输入的历史命令tab
键 - 列出当前命令.help
- 列出使用命令.break
- 退出多行表达式.clear
- 退出多行表达式.save filename
- 保存当前的 Node REPL 会话到指定文件.load filename
- 载入当前 Node REPL 会话的文件内容。
回调函数
简介
- Node.js 异步编程的直接体现就是回调
- 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