create a http server and upload a file in typescript

Here is an example code snippet to create an HTTP server with Node.js and Express.js, which can handle file uploads:

index.ts
import express from 'express';
import http from 'http';
import multer from 'multer';

const app = express();
const server = http.createServer(app);

const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
  const file = req.file;
  // Do something with the uploaded file here...

  res.send('File uploaded successfully');
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});
456 chars
20 lines

In this example, we first import the necessary modules: express, http, and multer for handling file uploads.

We then create an instance of express and http.createServer() to create an HTTP server. We also create an instance of multer, specifying the destination folder for uploaded files.

Next, we define a POST route /upload, which expects a single file with the name file. When a file is uploaded to this route, upload.single() middleware from Multer will handle the upload, and the uploaded file will be available in req.file. You can then process and save the file to disk, or store it in a database.

Finally, we start the HTTP server by calling server.listen(), listening on port 3000.

gistlibby LogSnag