node.js启动服务,不依赖第三方

好好学习,天天向上,懒惰、颓废让我越来越糟糕,所以分享一下,共同学习
纯node.js搭建一个小服务,下图为文件目录结构,很简单,很小

log文件是自动生成的

index.js文件

const url = require('url');
const http = require('http');
const fs = require('fs');
const { Console } = require('console');

let hostname = '127.0.0.1';
let port = 8080;

var curURL = ''

// 读取文件,处理编码问题
function readText (pathname) {
  let bin = fs.readFileSync(pathname)
  if (bin[0] === 0xEF && bin[1] === 0xBB && bin[2] === 0xBF) {
    bin = bin.slice(3)
  }
  return bin.toString('utf-8')
}

// 获取当前的时间
function getCurrentDate () {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth()+1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  let curDate = year + '年' + month + '月' + day + '日 ' + hour + ':' + minute + ':' + second;
  return curDate
}

// 创建 HTTP 隧道代理
const server = http.createServer((req, res) => {
  var pathname = url.parse(req.url).pathname; 
    // 过滤掉favicon的请求,不然log里面会有这个url
    if(pathname !== '/favicon.ico'){
      curURL = `http://${hostname}:${port}${req.url}`
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.writeHead(200, { 'Content-Type': 'application/json' });
      console.log(readText('./user.json'))
      res.end(readText('./user.json'))
      getLog()
    }
});

// 打印日志模块
function getLog () {
  let options =  {
    encoding: 'utf-8',
    flags: 'w'
  }
  // 判断文件是否存在
  if (fs.existsSync('./Log.log')) {
    options.flags = 'r'
  }

  const output = fs.createWriteStream('./Log.log', options);
  const errorOutput = fs.createWriteStream('./Log.log',options);
  const logger = new Console({ stdout: output, stderr: errorOutput });
  // 获取当前的时间
  let curDate = getCurrentDate ()
  let logs = `[${curDate}]=====URL路径:${curURL}
`
  console.log(logs)
  // 将新的内容写入日志,并且不删除原来的
  fs.appendFile('./Log.log',logs,'utf8',function(err, ret) {
    if(err) {
      throw err
    }
  })
  logger.log(logs);
}

server.listen(port, hostname, () => {
  console.log(`服务运行在 http://${hostname}:${port}/`);
});
user.json 文件
1
{ 2 "name": "白晶晶(醉盏)", 3 "attr": "这是一个很懒的小仙女", 4 "server": "Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效" 5 }

打印结果:

网页输入地址:http://localhost:8080

原文地址:https://www.cnblogs.com/belove8013/p/11475731.html