create a http server on a specific port in typescript

To create a HTTP server in Typescript, we can use the Express.js framework along with Node.js. Follow the steps below to create a server on a specific port:

  1. Create a new Typescript project and install the necessary dependencies:
index.ts
npm init
npm install express body-parser typescript @types/node @types/express --save
86 chars
3 lines
  1. Create a new file called server.ts and add the following code to it:
index.ts
import express from 'express';

const app = express();
const port = 3000;

// Set up a basic route
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// Start the server on a specific port
app.listen(port, () => {
  console.log(`Server started at http://localhost:${port}`);
});
290 chars
15 lines
  1. Compile the TypeScript file into JavaScript using the command tsc server.ts. This will generate a new file called server.js.

  2. Run the server by executing the command node server.js

This will start the server and it will be accessible at http://localhost:3000/.

gistlibby LogSnag