复习node.js(上)

68 阅读2分钟

一、了解node.js

1.什么是node.js

  Node.js是一个基于chromeV8引擎的JavaScript运行环境 一、了解node.js

图片.png

2.如何在node.js中运行JavaScript代码

1.win+R打开终端

图片.png

2.cd + js的路径 切换到当前js所在的路径下面 3.node 空格+ js的名称 运行代码

图片.png

3.读取指定文件中的内容

语法格式fs.readFile()

  • 参数1 必选参数 要读取的文件路径
  • 参数2 可选参数 是以什么编码格式来读取文件 utf-8
  • 参数3 必选参数 回调函数 通过回调函数来读取文件中的内容
// 导入fs模块

const fs=require('fs');

fs.readFile('./1.txt', 'utf-8', function(err, dataStar){

    // 如果读取成功,则err的返回值是null

    console.log(err);

    // 读取成功后dataStar返回读取的结果

    console.log(dataStar);

})

4.向指定文件中写入内容

语法格式fs.writeFile()

  • 参数1 必选参数 要写入文件的路径
  • 参数2 必选参数 要写入的内容
  • 参数3 可选参数 以什么编码格式写入
  • 参数4 必选参数 回调函数
// 会覆盖本来就有的内容

fs.writeFile('./1.txt','快开学了','utf-8',function(err) {

    console.log(err);

})

5.Path路径模块

path.jon()语法格式

// 导入path路径模块

const path=require('path');

const pathstr=path.join('a/','/c/d/e','../','/w');

console.log(pathstr);

// 输出a\c\d\w

图片.png

path.extname(path)语法 获取文件的扩展名

参数1 必选参数path路径的字符串

// 获取路径中的文件名

const path=require('path');

const spath='/a/b/c/index.html';

const fullName=path.basename(spath);

console.log(fullName);

// 去除文件后缀

const widthout=path.basename(spath,'.html')

console.log(widthout);

// 获取文件扩展名.html

const fpath=path.extname(spath);

console.log(fpath);

二、创建web服务器

1.导入http的模块

// 创建web服务器

// 1.导入http模块

const http=require('http');

// 2.创建web服务器实例

const server=http.createServer()

// 3.为服务器实例绑定request事件,监听客户端请求

server.on('request',function(req,res){

  console.log('Someine visit our web server');

})

// // 4.启动服务器

server.listen(8080,function(){

  console.log('server runing at http://127.0.0.1:8080');

})

req请求对象

图片.png

req是请求对象,它包含了与客户端相关的数据和属性,例如:

req.url是客户端相关的数据和属性,例如:

req.url是客户端请求的url地址

req.method 是客户端的method请求类型

res请求对象

res是响应对象,它包含了与服务器相关的数据和属性,例如:

要发送到客户端的字符串

2.解决中文乱码问题

使用res.send()方法时,向服务器端发送内容可能会出现乱码问题


// 中文会出现乱码问题  设置响应头

   res.setHeader('Content-Type', 'text/html;charset=utf-8')

   //把str发送给客户端

  res.end(str);