六行代码搭建静态网站

很多人觉得用 SpringBoot 开发后端服务太方便了,但是 Node.js 可能比 SpringBoot 更方便,用 SpringBoot 你要按部就班先新建一个工程,然后再写逻辑代码,但用 Node.js 直接拿一个 js 文件就开写,写完直接一条命令 node xx.js 就跑起来了,启动速度也甩 SpringBoot 几条街。

不得不承认 node 很简洁、高效,甚至可以说,在 Node.js 面前,Java 的 Spring 框架显得有些臃肿不堪。

比如要搭一个静态网页,node 只需六行代码就可以搞定。

node 搭建静态博客

就拿我的博客为例,先从 github 上把博客的网页源码下载下来:

https://github.com/yunTerry/yunTerry.github.io

把这些静态 html、css、js 网页文件放在电脑 D 盘 blog 文件夹下,路径:D:/blog/,新建一个 app.js 中加入如下代码:

1
2
3
4
5
6
7
8
const express = require('express')
const app = express()

app.use(express.static('D:/blog/'))

app.listen(5000, () => {
console.log('启动服务 http://localhost:5000')
})

然后执行 node app.js ,浏览器打开 http://localhost:5000 就能看到网页服务就跑起来了:

当然运行这段代码需要 express 模块,全局安装 express 模块:

1
npm install -g express

也可以简写成

1
npm i -g express

其他方式搭建

当然用 SpringBoot 搭建也很简单,只需三行配置:

1
2
3
server.port=5000
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:D:/blog/

或者用 Nginx 也很简单:

1
2
3
4
5
6
7
8
server {
listen 5000;

location / {
root D:/blog;
index index.html index.htm;
}
}