app.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const http = require('http')
  2. const fsPromises = require('fs').promises
  3. const path = require('path')
  4. const crypto = require('crypto')
  5. const sleep = require('util').promisify(setTimeout)
  6. const argvIndexOfFile = process.argv.indexOf(__filename)
  7. let SLEEP_TIME = parseInt(process.argv[argvIndexOfFile + 1])
  8. if (isNaN(SLEEP_TIME)) {
  9. SLEEP_TIME = 200
  10. }
  11. let PORT = parseInt(process.argv[argvIndexOfFile + 2])
  12. if (isNaN(PORT)) {
  13. PORT = 8000
  14. }
  15. function sha384(data) {
  16. const hash = crypto.createHash('sha384')
  17. hash.update(data)
  18. return hash.digest('base64')
  19. }
  20. async function requestListener(req, res) {
  21. await sleep(SLEEP_TIME)
  22. let headers = {
  23. 'Content-Type': 'text/html',
  24. }
  25. let pathString = req.url.substr(1)
  26. let page = parseInt(pathString)
  27. if (pathString == '') {
  28. page = 1
  29. }
  30. let content = ''
  31. const jsContent = await fsPromises.readFile(path.resolve(__dirname, '../instantpage.js'))
  32. const jsHash = sha384(jsContent)
  33. if (pathString == 'instantpage.js') {
  34. headers['Content-Type'] = 'text/javascript'
  35. content += jsContent
  36. }
  37. else if (!isNaN(page)) {
  38. content += await fsPromises.readFile(path.resolve(__dirname, 'header.html'))
  39. content += `<h1>Page ${page}</h1>`
  40. for (let i = 1; i <= 3; i++) {
  41. if (page != i) {
  42. content += `<a href="/${i}?${Math.random()}">Page ${i}</a>`
  43. }
  44. }
  45. content += `<a href="${req.url}#anchor" id="anchor">Same-page anchor</a>`
  46. content += `<a href="/${page}?${Math.random()}#anchor">Other page anchor</a>`
  47. content += `<a href="/${page}?${Math.random()}" data-instant="no">Manually blacklisted link</a>`
  48. content += `<a href="https://www.google.com/">External link</a>`
  49. let footer = await fsPromises.readFile(path.resolve(__dirname, 'footer.html'))
  50. footer = footer.toString().replace('__HASH__', jsHash)
  51. content += footer
  52. }
  53. res.writeHead(200, headers)
  54. res.write(content)
  55. res.end()
  56. }
  57. http.createServer(requestListener).listen(PORT)