Skip to content

Instantly share code, notes, and snippets.

@msarchet
Last active November 2, 2016 05:35
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 msarchet/d630edffda1522fa8dc0ad238969fdc0 to your computer and use it in GitHub Desktop.
Save msarchet/d630edffda1522fa8dc0ad238969fdc0 to your computer and use it in GitHub Desktop.
A Javascript file that acts as both a nodejs webserver and the index.html for the site that it serves
//<html>
// <head>
// <title>Self Server</title>
// </head>
// <body>
// <h1>Explanation here: https://gist.github.com/msarchet/d630edffda1522fa8dc0ad238969fdc0</h1>
// <script type='text/javascript'>
// var process = { env: { server: false } }
if (process.env.server) {
const http = require('http')
const fs = require('fs')
let readSelfPromise = null
const readSelf = () => {
readSelfPromise = readSelfPromise || new Promise((resolve, reject) => {
fs.readFile('./selfserver.js', 'utf-8', (err, file) => {
if (err) {
reject(err)
return
}
resolve(file.replace(/\/\//g, '').replace('/\\/\\g', "/\\/\\//g"))
})
})
return readSelfPromise
}
const server = http.createServer((request, response) => {
if (request.url === '/') {
readSelf().then(html => {
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end(html, 'utf-8')
}).catch(err => {
response.writeHead(500)
response.end(JSON.stringify(err))
})
} else {
response.writeHead(403)
response.end('Not Allowed')
}
})
server.listen(8080)
} else {
setTimeout(function() {
var header = document.getElementsByTagName('h1')[0]
var fromJs = document.createElement('h1')
fromJs.innerText = 'From javascript'
header.insertAdjacentElement('afterend', fromJs)
}, 1500)
}
// </script>
// </body>
//</html>
@msarchet
Copy link
Author

msarchet commented Nov 2, 2016

Run this file to node, and point your browser to http://localhost:8080

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment