Read the port number from the environment variable file
Use dotenv
import dotenv from 'dotenv';
dotenv.config();
const port = process.env.PORT;`
Create a HTTP server and listen to the given port
...
import * as http from 'http';
...
const server = http.createServer();
server.listen(port, () => {
console.log('Server started');
});
Check the server running status
Pass a function (request, response) => { // do something }
into createServer
as the request handler. When the http server receives a HTTP request, the request handler will handle it.
For example, set the response header (status code 200 and the response type), send a text as a response to the client, and then end the response object (which is a WritableStream
):
...
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello!\n');
});
...
Open a browser to test
Reference
- https://blog.logrocket.com/websocket-tutorial-real-time-node-react/#use-websockets-node-js-react
- https://dhruv-saksena.medium.com/websocket-development-with-typescript-from-scratch-782436d3e3be
- https://stackabuse.com/how-to-start-a-node-server-examples-with-the-most-popular-frameworks/
- https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction
Top comments (0)