node.js启动服务,不依赖第三方
2024-10-20 04:06:49
好好学习,天天向上,懒惰、颓废让我越来越糟糕,所以分享一下,共同学习
纯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
最新文章
- Google V8编程详解(五)JS调用C++
- String类字符串截取示范
- linux基础-第六单元 用户、群组和权限
- MVC 增删改查
- 杨氏矩阵 leecode 提
- 利用python分析nginx日志
- C语言实现两栈空间共享
- hadoop2.2.0 MapReduce分区
- JavaScript中prompt()函数的用法。
- final关键字修饰的变量
- Asp.Net Core-----简介与安装
- java 集合框架(十六)Map
- 纯HTML5APP与原生APP的差距在哪?
- WelcomeActivity【欢迎界面】
- Linux 6.8 源码安装MySQL8.0
- 使用visual C++测试
- Entity framework中LINQ的使用
- WebView性能、体验分析与优化
- 面向的phthon2+3 的场景,Anaconda 安装+环境配置+管理
- linux下正则表达式学习