Linux使用Node.js建立访问静态网页的服务实例详解

作者:袖梨 2022-06-30

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

相关文章

精彩推荐