Formidable returns TypeError, ERR_INVALID_ARG_TYPE: The "path" argument is undefined
I'm having trouble uploading files using formidable. I'm on Windows server 2016.
My code, which in its entirely is shown below, is based on https://www.geeksforgeeks.org/how-to-upload-file-using-formidable-module-in-node-js/
const express = require('express');
const fs = require('fs');
const path = require('path')
const formidable = require('formidable');
const app = express();
app.post('/api/upload', (req, res, next) => {
const form = new formidable.IncomingForm(
{ uploadDir: __dirname + '\\tmp', keepExtensions: true }
);
form.parse(req, function(err, fields, files){
var oldPath = files.profilePic.path;
var newPath = path.join(__dirname, 'uploads')
+ '/'+files.profilePic.name
var rawData = fs.readFileSync(oldPath)
fs.writeFile(newPath, rawData, function(err){
if(err) console.log(err)
return res.send("Successfully uploaded")
})
})
});
app.listen(3000, function(err){
if(err) console.log(err)
console.log('Server listening on Port 3000');
});
I use Postman to send a file.
When triggering the /api/upload
API, the file sent is correctly placed in the tmp folder, but reading the path is when the problem arise:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
This message points to fs.readFileSync(oldPath)
.
console.log('files='+files)
returns files=[object Object]
console.log('files.profilePic='+files.profilePic)
returns
C:\somepath\node_modules\formidable\src\PersistentFile.js:50
return `PersistentFile: ${this._file.newFilename}, Original: ${this._file.originalFilename}, Path: ${this._file.filepath}`;
^
TypeError: Cannot read properties of undefined (reading 'newFilename')
at PersistentFile.toString (C:\somepath\node_modules\formidable\src\PersistentFile.js:50:42)
All 4 referenced modules exist in node_modules folder.
Simply change
var oldPath = files.profilePic.path;
to
var oldPath = files.profilePic.filepath;
Also make sure that you create the "uploads" folder as the code doesn't create it and it will fail without it.
EDIT: A side note is that if your environment is just spitting out [object object] when you console log an object, then probably get a new environment (visual studio code is good) that gives useful information.