好好学习,天天向上,懒惰、颓废让我越来越糟糕,所以分享一下,共同学习
纯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}\n`
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 {
"name": "白晶晶(醉盏)",
"attr": "这是一个很懒的小仙女",
"server": "Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效"
}

打印结果:

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

最新文章

  1. Google V8编程详解(五)JS调用C++
  2. String类字符串截取示范
  3. linux基础-第六单元 用户、群组和权限
  4. MVC 增删改查
  5. 杨氏矩阵 leecode 提
  6. 利用python分析nginx日志
  7. C语言实现两栈空间共享
  8. hadoop2.2.0 MapReduce分区
  9. JavaScript中prompt()函数的用法。
  10. final关键字修饰的变量
  11. Asp.Net Core-----简介与安装
  12. java 集合框架(十六)Map
  13. 纯HTML5APP与原生APP的差距在哪?
  14. WelcomeActivity【欢迎界面】
  15. Linux 6.8 源码安装MySQL8.0
  16. 使用visual C++测试
  17. Entity framework中LINQ的使用
  18. WebView性能、体验分析与优化
  19. 面向的phthon2+3 的场景,Anaconda 安装+环境配置+管理
  20. linux下正则表达式学习

热门文章

  1. java中instanceof的基本使用
  2. 白盒测试笔记之:Junit 单元测试以及测试覆盖率
  3. C#实现多线程的方式:使用Parallel类
  4. TCP和SSL TCP应用
  5. ZooKeeper的ACL权限
  6. 简单了解运用Git
  7. js执行多次事件,而非一次
  8. 从入门到自闭之Python编码
  9. Zabbix 配置钉钉脚本告警
  10. IdentitiServser4 + Mysql实现Authorization Server