- A+
所属分类:Web前端
什么是node
- Javascript可以在浏览器运行, node可以让javascript在浏览器之外运行
- 可以用来做本地运行的软件/网络服务器/游戏等等
记得安装vs code里面力扣插件需要先安装node.js, 但我不知道node是做什么的
Last login: Fri Sep 22 13:34:30 on ttys003 l@away ~ % node zsh: command not found: node
本地还没有安装node, 下面开始安装
安装node
- 登陆node官网下载
- 选择左边稳定版本
- 安装pkg⬇️
continue- continue- agree- continue- install
- 安装完成✅
终端terminal里面输入node可以看到版本号/node -v
- ctrl+c两次/ctrl+d/.exit退出
l@away ~ % node Welcome to Node.js v18.18.0. Type ".help" for more information. > > > > > (To exit, press Ctrl+C again or Ctrl+D or type .exit) >
Node REPL
- 和浏览器中的console界面类似
l@away ~ % node Welcome to Node.js v18.18.0. Type ".help" for more information. > .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 > 1 + 2 3 > "hello" + "world" 'helloworld'
global scope可以输入global查看
使用global下面的function
> setTimeout(() => {console.log("Heloo")}, 3000) Timeout { _idleTimeout: 3000, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 398982, _onTimeout: [Function (anonymous)], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: true, [Symbol(kHasPrimitive)]: false, [Symbol(asyncId)]: 365, [Symbol(triggerId)]: 6 }
- 和客户端JS区别
- node不是在浏览器上运行, 不能对浏览器中的window/document/DOM API进行操作
- 可以和操作系统/文件系统进行交互
如何运行一个脚本
- terminal新建文件
touch firstTest.js
- vs code编辑此文件
for(let i = 0; i < 10; i++) { console.log("hello from first script!!") }
- terminal通过命令行
node filename
运行
l@away code % touch firstTest.js l@away code % node firstTest.js hello from first script!! hello from first script!! hello from first script!! hello from first script!! hello from first script!! hello from first script!! hello from first script!! hello from first script!! hello from first script!! hello from first script!! l@away code %
命令行传入参数
- vs code 编辑脚本文件
通过process.argv.slice(2)
获得参数的list
其中argv的第一个'/usr/local/bin/node'是运行路径, 第二个'/Users/code/args.js'是运行的脚本文件所在路径
console.log("hello from args", process.argv); const personList = process.argv.slice(2); for (p of personList) { console.log(`hello, ${p}`); }
- terminal运行时
node filename arg1 arg2 aeg3
传入参数
l@away code % node args.js person1 person2 person3 hello from args [ '/usr/local/bin/node', '/Users/code/args.js', 'person1', 'person2', 'person3' ] hello, person1 hello, person2 hello, person3