Based on this answer
With folder called assets
contains app.css
and jquery.js
, also server.js
and index.html
with following content hopefully you could get your desired result.
server.js
const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const port = process.argv[2] || 8888;
const contentTypes = {
'.html': "text/html",
'.css': "text/css",
'.js': "text/javascript"
};
http.createServer((req, res) => {
let uri = url.parse(req.url).pathname;
if (uri.indexOf('/api/getall') > -1 ) {
// simulate database delay
setTimeout(() => {
res.writeHead(200, {"Content-Type": "application/json"});
res.write(JSON.stringify({id: 10}));
res.end();
}, 1000);
}
else {
let filename = path.join(process.cwd(), uri);
fs.exists(filename, exists => {
if(!exists) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404 Not Foundn");
res.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", (err, file) => {
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.write(err + "n");
res.end();
return;
}
let headers = {},
contentType = contentTypes[path.extname(filename)];
if (contentType) headers["Content-Type"] = contentType;
res.writeHead(200, headers);
res.write(file, "binary");
res.end();
});
});
}
}).listen(parseInt(port, 10));
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title></title>
<link href='/assets/app.css' rel='stylesheet' />
</head>
<body>
<h1>Hello world!</h1>
<script src='/assets/jquery.js'></script>
<script>
$.ajax('/api/getall').done(res => console.log(res));
</script>
</body>
</html>
Run the app using node server.js
and head to http://localhost:8888/
, you should see Hello world
on the screen and { id: 10 }
on browser console. from there you can decide how to render your data, e.g using react
or mustache.js