-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfileServer.js
More file actions
33 lines (31 loc) · 1.01 KB
/
fileServer.js
File metadata and controls
33 lines (31 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
'use strict';
import fs from 'fs';
import http from 'http';
import path from 'path';
import url from 'url';
import koa from 'koa';
const workDir = path.resolve('.');
const hostname = '127.0.0.1';
const port = 4000;
console.log('Static root dir: ' + workDir);
//创建文件服务器
const server = http.createServer((request, response) => {
const pathname = url.parse(request.url).pathname;
const filePath = path.join(workDir, pathname);
fs.stat(filePath, (err, stat) => {
if (!err && stat.isFile()) {
response.writeHead(200);
fs.createReadStream(filePath).pipe(response);
} else if(!!stat.isDirectory()) {
response.writeHead(200);
fs.createReadStream(`${filePath}/index.html`).pipe(response);
} else {
console.log('404 ' + request.url);
response.writeHead(404);
response.end('404 Not Found');
}
});
});
server.listen(port, hostname, () => {
console.log('The Server is running at port:4000');
});