Skip to content

Instantly share code, notes, and snippets.

@monkindey
Last active August 19, 2017 03:21
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 monkindey/fc7f3ae3a1886aba74889f9e6cdb1e42 to your computer and use it in GitHub Desktop.
Save monkindey/fc7f3ae3a1886aba74889f9e6cdb1e42 to your computer and use it in GitHub Desktop.
html resolve js file

How HTML resolve JavaScript file

The folder like it

|____public
| |____index.html
| |____index.js
|____server.js

and node server.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="./index.js"></script>
</head>
<body>
<img id="img" height="300px" src="https://avatars3.githubusercontent.com/u/6913898?v=4&s=460" alt="basketry">
</body>
</html>
console.log('hello');
const http = require('http');
const path = require('path');
const fs = require('fs');
const public = path.resolve(__dirname, './public');
http
.createServer((req, res) => {
let filePath = path.resolve(public, req.url.slice(1));
let rs = fs.createReadStream(filePath);
rs &&
rs.on('error', e => {
if (e.code === 'ENOENT') {
res.end('404 Not Found');
}
});
if (path.extname(filePath) == '.js') {
// after 2s
setTimeout(() => {
rs.pipe(res);
}, 2000);
} else {
rs.pipe(res);
}
})
.listen(3018, () => {
console.log('At 3018');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment