create a http server and upload a file and return a json response in typescript

To create a HTTP server in TypeScript, we can use Node.js built-in http module. Here is an example of creating an HTTP server, handling file uploads and returning a JSON response:

index.ts
import http from 'http';
import { parse } from 'querystring';
import * as fs from 'fs';

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk.toString();
    });
    req.on('end', () => {
      const data = parse(body);
      const fileName = data.fileName;
      const fileContent = data.fileContent;
      fs.writeFile(fileName, fileContent, err => {
        if (err) {
          res.statusCode = 500;
          res.end(JSON.stringify({ message: 'Error writing file' }));
        } else {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'application/json');
          res.end(JSON.stringify({ message: 'File uploaded successfully' }));
        }
      });
    });
  } else {
    res.statusCode = 404;
    res.end();
  }
});

const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log(`Server running at port ${port}`);
});
969 chars
36 lines

This code listens for a POST request, reads the data from the request body, saves the file to the server, and returns a JSON response with either a success or error message.

Note: This code does not include any additional security measures or file size limits, and should be further optimized for production use.

gistlibby LogSnag