Node.js第一节
定义:Node.js是一个应用编程平台,能运行JS写的代码,基于Google的V8引擎,也就是js代码能通过Node.js直接查看。
下载:
链接: link.
下载好后,通过Windows命令行窗口执行 node -v 来检查安装成功没有,命令行窗口出现 版本号 就安装完成。
如下图所示:
node.js 的使用
推荐在viscode中打开。
步骤1: 右键点击要使用文件,然后点击在集成终端打开。
图示:
步骤2: 在下面弹出的命令行输入指令。
步骤3: 修改默认值为cmd。
图示:
node.js常用指令
指令 | 含义 |
---|---|
dir | 查看当前文件夹下的所有文件 |
tree | 以树状图结构展示当前目录下所有文件及子目录下所有文件 |
cd 文件夹 | 进入当前目录下的某一个目录 |
cd… | 返回上一个目录 |
D: | 切换盘符 |
cls | 清空命令行窗口 |
ipconfig | 查看当前电脑的id地址 |
ping www.baidu.com | 查看百度网速 |
systeminfo | 查看当前电脑信息 |
md test | 创建一个名为test文件夹 |
rd test | 移除当前文件夹下的名为test文件夹 |
xcopy test test1 | 复制一份test文件夹起名为test1 |
type nul>index,js | 在当前目录下创建一个名为index.js文件 |
copy index.js | 复制一份index.js文件 |
echo console.log(‘hello world’)>index.js | 向index.js文件中写入文本console.log(‘hello world’) |
type index.js | 查看index.js中内容 |
ren index.js second.js | 将index.js重命名为second.js |
del index.js | 删除index.js |
move index.js a | 移动index.js到a文件夹下 |
node index.js | 运行index.js |
ctrl+c | 停止运行 |
实例操作
web服务器
第一步: 引入node.js的http模块。
第二步: 创建web服务对象。
request请求对象,前端请求
response响应对象
第三步: 启动web服务器,监听端口,端口区分同一台电脑中不同web应用。
示例:
//调用内部模块require
var http=require('http')
//构造一个服务(接受两个参数request浏览器请求,response返回给浏览器的结果)
var server=http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/plain'})
response.write('hello world')
response.end()
})
//监听3000端口
server.listen(3000)
//用于成功启动时输出server started linsten 3000
console.log('server started linsten 3000');
//当在浏览器窗口输入http://localhost:3000
//页面出现hello world
注:当无法打开时
1. 检查端口是否正确
2. 查看服务器是否在本地,如果不在的话,需要将localhost替换为服务器ip
3. 检查电脑防火墙是否对此类端口开放