nodejs页面输出html,用nodejs创建服务器显示html页面

nodejs版本:v10.14.2

1.首先准备一个简单的html页面

1

2

3

4

5

nodejs显示html

6

7

8

看到这句话表示html页面成功显示了。

9

10

2.接着准备一个index.js,跟index.html放在同一目录下

(1)导入需要用到的模块,都是nodejs自带的模块

const http = require("http"),

fs = require("fs"),

path = require("path"),

url = require("url");

创建服务器当然需要http模块了,fs模块用来读写html的,path模块用来获取当前目录的,url模块用来解析输入的url的

(2)获取当前目录

// 获取当前目录

var root = path.resolve();

因为index.html和index.js是放在一起的,属于同级,直接获取当前目录就行了。

(3)创建服务器

// 创建服务器

var sever = http.createserver(function(request,response){

var pathname = url.parse(request.url).pathname;

var filepath = path.join(root,pathname);

// 获取文件状态

fs.stat(filepath,function(err,stats){

if(err){

// 发送404响应

response.writehead(404);

response.end("404 not found.");

}else{

// 发送200响应

response.writehead(200);

// response是一个writestream对象,fs读取html后,可以用pipe方法直接写入

fs.createreadstream(filepath).pipe(response);

}

});

});

sever.listen(8080);

console.log('sever is running at http://127.0.0.1:8080/');

createserver方法创建一个sever,每次请求从request拿到url,解析后找到文件,获取成功后写入response。

失败则发送404.

代码部分到此结束,接下来是测试

(4)测试

打开cmd,找到文件所在目录(当然用vs code之类更方便,敲代码测试都在一起),键入node index.js

0e48c935f783f3999044bc84052cb6c6.png

可以看到输出sever is running at http://127.0.0.1:8080/,表示服务器已经搭建好了。

接着打开浏览器,输入

43a961f825cd2a831203083e80dc4068.png

成功了!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值