create a http server and upload a file in javascript

To create an HTTP server and handle file uploads in Node.js, we can use the built-in http and fs modules. Here's a basic example:

index.tsx
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', data => {
      body += data;
    });
    req.on('end', () => {
      const filename = req.headers['x-filename'];
      fs.writeFile(filename, body, err => {
        if (err) {
          console.error(err);
          res.statusCode = 500;
          res.end('Error uploading file');
        } else {
          res.end('File uploaded successfully');
        }
      });
    });
  } else {
    res.setHeader('Content-Type', 'text/html');
    res.write('<form action="/" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="file"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    res.end();
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
925 chars
35 lines

This creates an HTTP server that listens on port 3000. When a GET request is received, it sends back an HTML form that allows the user to select a file to upload. When a POST request is received, it reads the contents of the uploaded file and saves it to disk.

Note that this example doesn't handle file size limits, file type restrictions, or any other security concerns. It's just a simple example to get started with file uploading in Node.js.

gistlibby LogSnag