const http = require('http');const formidable = require('formidable');const mv = require('mv');const fs = require('fs');const path = require('path');const server = http.createServer((req, res) => { if (req.url === '/upload'&& req.method.toLowerCase() === 'post') { const form = new formidable.IncomingForm(); const uploadDir = path.join(__dirname, 'uploads'); form.uploadDir = uploadDir; //check if folder does not exist if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir); } form.parse(req, (err, fields, files) => { if (err) { console.error('Error parsing form:', err); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal Server Error'); return; } const oldPath = files.file.path; const newPath = path.join(uploadDir, files.file.name); //{ mkdirp: true }: An options object passed to the mv function. The mkdirp option is used to create any necessary directories in the destination path (newPath) if they don't already exist. In other words, it automatically creates parent directories as needed. mv(oldPath, newPath, { mkdirp: true }, (err) => { if (err) { console.error('Error moving file:', err); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal Server Error'); return; } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('File uploaded and moved!'); }); }); return; } res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(`<form action="/upload" method="post" enctype="multipart/form-data"><input type="file" name="file"><br><input type="submit" value="Upload"></form> `);});const PORT = 3000;server.listen(PORT, () => { console.log(`Server listening on http://localhost:${PORT}`);});
Use this above code, I have used mv library to rename or move files and it worked.On my Mac machine Rename was not working and giving same error. Maybe someone finds this solution to work.