Skip to content

Commit

Permalink
feat: working mvp of a good enough server for express and socket io
Browse files Browse the repository at this point in the history
  • Loading branch information
3p3r committed Oct 31, 2023
0 parents commit 836d784
Show file tree
Hide file tree
Showing 15 changed files with 5,655 additions and 0 deletions.
130 changes: 130 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Sepehr Laal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
98 changes: 98 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# fakettp

fake browser side http server via service workers with node api compatibility.

# usage

## bundlers

you can alias `http` to `fakettp` in your bundler config to use it as a drop in
replacement for node's http module. Example webpack config:

```sh
npm install fakettp --save-dev
```

```js
module.exports = {
resolve: {
alias: {
http: "fakettp",
},
// or
fallback: {
http: require.resolve("fakettp"),
}
},
};
```

## browsers

this is a library primarily intended for use in bundlers like webpack.
example use case would be running an express app or socket io app locally.

a single global variable `FAKETTP` is exposed which partially implements socket,
net.stream, and net.server, and net.http interfaces from node.

it currently implements enough to run most express and socket io apps untouched.
socket io needs to be tuned in client side to use polling and not web sockets.

`http.createServer` is the main entry point (or rather `FAKETTP.createServer`).
fakettp is built into a UMD module, so it can be used in bundlers or browsers.

# example

![demo](./ext/demo.png)

You can create a server and listen like so:

```js
FAKETTP.createServer().on("request", (req, res) => {
req.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data in request body.`);
console.log(`Request chunk: ${chunk.toString()}`);
});
req.on('end', () => {
console.log('No more data in request body.');
});
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('{"yo":"nice"}');
}).listen();
```

![listen](./ext/listen.png)

After that all requests will be intercepted and handled by the service worker.
Only requests to the same origin will be intercepted (excluding worker itself).
The HTML page loading the worker is also excluded from interception.

You can for example send a request to the server like so:

```js
async function postData(data = {}, url = "test.html") {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return response.json();
}

postData({ answer: "browser" }).then((data) => {
console.log(data);
});
```

![response](./ext/response.png)

# development

- Run `npm run build` to build the project.
- Run `npm run serve` to start webpack dev server.
- Run `npm run watch` to watch for changes and rebuild.
- Run `npx http-serve --cors dist` to run production build.

in dev modes, verbose logging is enabled. in production, it is disabled.
Binary file added ext/demo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ext/listen.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ext/response.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 836d784

Please sign in to comment.