Node.js搭建简单服务器教程

Node.js搭建一个简单服务器其实蛮,适合初学者或想快速搞定原型的开发者。只要你会点 JavaScript,就能在服务器端写代码,完全不需要担心后端语言。你需要用到几个核心模块:urlpathfshttpurl模块帮你解析 HTTP 求中的路径,path模块文件路径,fs模块文件系统的操作,http模块则是用来创建服务器的。代码也简单,像这样:

'use strict';
const url = require('url');
const path = require('path');
const fs = require('fs');
const http = require('http');

const root = process.argv[2] ? path.resolve(process.argv[2]) : path.resolve('.'); console.log('本地根目录:', root);

const server = http.createServer((request, response) => { const pathname = url.parse(request.url).pathname; const filepath = path.join(root, pathname); fs.stat(filepath, (err, stat) => { if (!err && stat.isFile()) { console.log(`200 ${request.url}`); response.writeHead(200); fs.createReadStream(filepath).pipe(response); } else { console.log(`404 ${request.url}`); response.writeHead(404); response.end('404 Not Found'); } }); });

server.listen(8080); console.log('服务器正在运行于 http://127.0.0.1:8080/');

这里求路径,检查文件是否存在,如果存在就返回,没找到就报 404。你可以用它来当做本地测试服务器。稍微复杂的项目用Express.js会更加方便。,挺简单也蛮有趣的,值得试试!

pdf 文件大小:60.51KB