Created
June 9, 2023 02:36
-
-
Save mntone/ccb51192a6e215c20faf39107ff441f9 to your computer and use it in GitHub Desktop.
Simply nodejs server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MIT: Copyright (C) 2023 mntone. All rights reserved. | |
const fs = require('fs') | |
const path = require('path') | |
const http = require('http') | |
const port = 80 | |
const dirPublic = './' | |
const indexFile = 'index.html' | |
const service = (req, res) => { | |
const pathname = req.url | |
const root = path.resolve(dirPublic) | |
const file = path.join(root, pathname) | |
fs.stat(file, (err, stat) => { | |
if (err) { | |
console.log('err', err) | |
res.write('err') | |
res.end() | |
return | |
} | |
if (stat.isDirectory()) { | |
service({ url: `${req.url}/${indexFile}` }, res) | |
} | |
if (stat.isFile()) { | |
const stream = fs.createReadStream(file) | |
stream.pipe(res) | |
} | |
}) | |
} | |
const listener = (req, res) => { | |
service(req, res) | |
} | |
const server = http.createServer(listener); | |
server.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment