Node.js - I can't upload files to local server - "The "oldPath" argument must be of type string..."

91 Views Asked by At

I've got a problem with uploading files to local server. When I'm trying to send the file, browser's showing an error ERR_CONNECTION_REFUSED, while my node console is throwing TypeError [ERR_INVALID_ARG_TYPE]: The "oldPath" argument must be of type string or an instance of Buffer or URL. Received undefined. I have formidable and fs installed and shown in my dependencies list in package.json. I was already googling this problem, but haven't found any solution.

Here's my code:

let http = require('http');
let formidable = require('formidable');
let fs = require('fs');

let htmlForm = `
    <html>
        <head></head>
        <body>
            <form method="post" action="/upload" enctype="multipart/form-data">
                <input type="file" name="upfile"><br>
                <input type="submit" value="Send">
            </form>
        </body>
    </html>
`;

http.createServer(function (req, res) {
    if (req.url === '/upload') {
        let form = new formidable.IncomingForm();

        form.parse(req, function (err, fields, files) {
            let tempPath = files.upfile.filepath;
            let newPath = './static/' + files.upfile.originalFilename;

            fs.rename(tempPath, newPath, function (err) {
                if (err) {
                    res.end('File upload error');
                } else {
                    res.end('Uploading complete!');
                }
            });
        });
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(htmlForm);
        res.end();
    }
}).listen(8080);

Any ideas why is this not working?

Tried to turn off my antivirus app and firewall, but this also doesn't help.

[EDIT] Ok, I'm losing my mind. Long story short, this piece of code I made during watching some course. Guy from course has uploaded his whole folder with the project, basically only node modules, servers.js file and package.json. I have downloaded that folder, opened it via VSCode, turned on the server, and I succesfully sent a file... But when I'm trying to do the same in my project that I was writing, it's still not working. I even changed all of the variables names in my project for the same as in working project, checked both server.js files in 'TextCompare!', both are EXACTLY the same, and the one from the course is working, but mine - not. The only difference is - I'm using newer versions of Node.js, Formidable (and so on) than him. Was there any changes in that extensions that could make issues with my code now?

Also, in Chrome DevTools, console is throwing this error

(index):6583 crbug/1173575, non-JS module files deprecated.
(anonymous) @ (index):6583
0

There are 0 best solutions below