如何使用Node.js搭建一个服务器

在node环境中运行下面的代码html

"use strict";

const http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs");

//path的resolve方法不传参数将返回当前工做目录的绝对路径
let root = path.resolve();

http.createServer(function(req, res){

  let filepath;

  //一般咱们访问网站的时候域名后面并不会加目录结构,因此当咱们直接输入域名的时候咱们让浏览器自动跳转到index.html
  if(req.url === "/"){
    //path的join方法能够将多个字符串用"\"拼接起来
    filepath = path.join( root, "index.html" );
  } else {
    filepath = path.join( root, req.url );
  }

  //判断你所要请求的是不是文件
  fs.stat(filepath, function(err, stats){
    if( !err && stats.isFile() ) {
      //设置响应头信息,能够防止中文乱码
      res.writeHead("200", {"content-type":"text/html; charset=utf-8"});
      //建立一个阅读流而且将filepath目录所在的文件内容发送给浏览器
      fs.createReadStream(filepath).pipe(res);
    } else {
      console.log("404");
      res.writeHead("404");
      res.end("404 Not Found");
    }
  });
//监听5000端口号,若是你的电脑的5000端口号被占用你能够使用其它的端口号
}).listen("5000");

console.log("Server start!!");

 

注:在上述代码的同一个目录下再建立一个index.html代码node

打开浏览器在地址栏中输入:localhost:5000/index.html便可将同一目录下的index页面在网页中打开浏览器

相关文章
相关标签/搜索