Skip to content

Instantly share code, notes, and snippets.

@mntone
Created June 9, 2023 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mntone/ccb51192a6e215c20faf39107ff441f9 to your computer and use it in GitHub Desktop.
Save mntone/ccb51192a6e215c20faf39107ff441f9 to your computer and use it in GitHub Desktop.
Simply nodejs server.
// 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