前言
nodejs是学习前端中不可或缺的知识,此贴为本人学习nodejs留下的笔记
REPL(交互式解释器)
REPL表示一个电脑环境,类似于Windows系统的终端Linux系统的Unix/LinuxShell,可以用来执行交互式命令。
node自带的交互式解释器有四种用途:
- 读取 读取用户输入,保存为JavaScript的数据结构并储存在内存中。
- 执行 执行输入的用户结构
- 打印 输出结果
- 循环 循环操作以上步骤直到用户两次按下 ctrl-c 按钮退出。
看完这些node的特点,让我感觉它的解释器非常想之前学过的python解释器,作用几乎相差无几。
输入node即可打开node终端
node
打开交互式解释器之后就可以在里面输入一些基本的js表达式,并且它会在下面输出结果。
> 1 + 4
5
> 9 / 2
4.5
> 5 * 5
25
变量的使用
和js语法一样,node中的变量使用var关键字来生成,如果不用var来声明控制台就会直接打印这个变量,如果希望打印变量可以使用console.log()方法来打印结果。
> var a = 1
undefined
> var b = 2
undefined
> a + b
3
多行表达式
REPL中支持多行表达式。
> var x = 0
undefined
> do {
... x ++ ;
... console.log("x:"+ x);
... }while(x<5);
x:1
x:2
x:3
x:4
x:5
undefined
…是系统自己生成的。
(_)变量
REPL支持使用_变量来表示上一个表达式返回的值。
> var a = 10;
undefined
> var b = 20;
undefined
> a + b;
30
> var num = _
undefined
> num
30
常用命令
- .help
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.editor Enter editor mode
.exit Exit the REPL
.help Print this help message
.load Load JS from a file into the REPL session
.save Save all evaluated commands in this REPL session to a file
Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL
.help命令可以查看一些常用的命令
-
ctrl+c
该命令可以退出当前终端
-
ctrl+两次c
该命令可以退出REPL交互式解释器 回到系统自带的终端环境 -
tab
tab键可以查看node中所有类名称
>
AbortController AbortSignal AggregateError
Array ArrayBuffer Atomics
BigInt BigInt64Array BigUint64Array
Blob Boolean BroadcastChannel
Buffer ByteLengthQueuingStrategy CompressionStream
CountQueuingStrategy DOMException DataView
Date DecompressionStream Error
EvalError Event EventTarget
FinalizationRegistry Float32Array Float64Array
FormData Function Headers
Infinity Int16Array Int32Array
Int8Array Intl JSON
Map Math MessageChannel
MessageEvent MessagePort NaN
Number Object Performance
Promise Proxy RangeError
ReadableByteStreamController ReadableStream ReadableStreamBYOBReader
ReadableStreamBYOBRequest ReadableStreamDefaultController ReadableStreamDefaultReader
ReferenceError Reflect RegExp
Request Response Set
SharedArrayBuffer String Symbol
SyntaxError TextDecoder TextDecoderStream
TextEncoder TextEncoderStream TransformStream
TransformStreamDefaultController TypeError URIError
URL URLSearchParams Uint16Array
Uint32Array Uint8Array Uint8ClampedArray
WeakMap WeakRef WeakSet
WebAssembly WritableStream WritableStreamDefaultController
WritableStreamDefaultWriter _ _error
assert async_hooks atob
btoa buffer child_process
clearImmediate clearInterval clearTimeout
cluster console constants
crypto decodeURI decodeURIComponent
dgram diagnostics_channel dns
domain encodeURI encodeURIComponent
escape eval events
fetch fs global
globalThis http http2
https inspector isFinite
isNaN module net
os parseFloat parseInt
path perf_hooks performance
process punycode querystring
queueMicrotask readline repl
require setImmediate setInterval
setTimeout stream string_decoder
structuredClone sys timers
tls trace_events tty
undefined unescape url
util v8 vm
worker_threads zlib
__proto__ hasOwnProperty isPrototypeOf
propertyIsEnumerable toLocaleString toString
valueOf
constructor
- .break
.break命令可以使程序退出多行表达式
> var a = function(){
...
...
... var b = 10;
... .break
>
回调函数
nodejs中的异步编程主要体现就是回调函数,回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Node 所有 API 都支持回调函数。
阻塞函数实例:
// 阻塞函数实例
var fs = require("fs");
var data = fs.readFileSync('123.txt');
console.log(data);
console.log("程序执行结束")
结果:
PS > node js回调函数.js
<Buffer e9 87 87 e7 94 a8 e8 bf 99 e7 a7 8d e6 96 b9 e5 bc 8f ef bc 8c e6 88 91 e4 bb ac e6 8a 8a e5 90 8c e6 ad a5 e6 93 8d e4 bd 9c e5 8f 98 e6 88 90 e4 ba ... 656 more bytes>
程序执行结束
可以看到这样的函数运行会等待文件被读取完再打印“程序执行结束”到控制台,增加了程序运行的时间,异步编程的重要性体现出来了。
非阻塞代码实例:
//非阻塞代码示例
var fs = require("fs");
fs.readFile('123.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString);
});
console.log('程序执行结束');
> node js回调函数.js
程序执行结束
[Function: toString]
第二个实例我们不需要等待文件读取完,这样就可以在读取文件时同时执行接下来的代码,大大提高了程序的性能。
因此,阻塞是按顺序执行的,而非阻塞是不需要按顺序的,所以如果需要处理回调函数的参数,我们就需要写在回调函数内。