最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Linux使用Node.js建立访问静态网页的服务实例详解
时间:2022-06-30 16:04:13 编辑:袖梨 来源:一聚教程网
Linux使用Node.js建立访问静态网页的服务实例详解
一、安装node.js运行所需要的环境,:http://www.**jb5*1.net/article/79536.htm
二、创建node目录(/node/www),并在目录下创建node.js服务文件server.js
| 代码如下 | 复制代码 |
|
var http = require('http');
var fs = require('fs');//引入文件读取模块
var documentRoot = ‘/node/www'//需要访问的文件的存放目录
var server= http.createServer(function(req,res){
var url = req.url; //客户端输入的url,例如如果输入localhost:9999/index.html //那么这里的url == /index.html
var file = documentRoot + url; console.log(url);//node/www/index.html
/* file为文件路径 function为回调函数, function的err为读取错误返回的信息,返回空就没有错误 function的data为读取成功返回的文本内容 */ fs.readFile( file , function(err,data){ if(err){ res.writeHeader(404,{ 'content-type':'text/html;charset="utf-8"' }); res.write(' 404错误你要找的页面不存在 '); res.end(); }else{ res.writeHeader(200,{ 'content-type':'text/html;charset="utf-8"' }); res.write(data);//将index.html显示在客户端 res.end(); }
});
}).listen(9999);
console.log('服务器开启成功...'); | |
三、创建index.html首页文件,放在路径为/node/www/下面
四、启动服务命令:node server.js
五、浏览器输入地址:http://loca*lho*s*t:9999/index.html
相关文章
- 原神2025最新兑换码有哪些 限时前瞻福利领取 11-16
- 百炼英雄2025兑换码大全 最新礼包福利领取合集 11-16
- 寻道大千2025兑换码 最新可用的礼包码合集 11-16
- 蛋仔派对2025兑换码 最新礼包码合集 11-16
- 元气骑士2025兑换码大全 最新可用礼包码合集 11-16
- 明日方舟终末地测试资格查询入口 官方验证方法一览 11-16