首页 > 技术文章 > 前端本地起服务

bear-blogs 2019-06-15 12:43 原文

一、http-server

1.全局安装http-server

npm i http-server -g

2.在当前的文件夹中运行http-server

http-server -o
// 或者
hs -o

 

二、nodejs

1.安装nodejs

2.编写server.js

const http = require('http');
const fs = require('fs');//引入文件读取模块
const { exec } = require("child_process");
const documentRoot = 'E:/learn/node';

http.createServer(function (req, res) {
  const file = documentRoot + req.url;
  fs.readFile(file, function (err, data) {
    if (err) {
      res.write('<h1>404</h1>');
      res.end();
    } else res.end(data);
  });
}).listen(8888);

const url = 'http://127.0.0.1:8888/index.html';
// win系统:win32   mac系统:darwin
const type = process.platform === 'win32' ? 'start' : 'open';
// 自动打开浏览器
exec(`${type} ${url}`);

console.log('服务器开启中...');

3.运行server.js

node server.js

 

推荐阅读