nodejs read file sent in the request without saving to file system

nodejs read file sent in the request without saving to file system

Reading a file sent in the request without saving it to the file system is a relatively straightforward task using Node.js. The first step is to install the formidable package from npm. This package allows us to parse the form data and access the file data. Once the package is installed, we can use the IncomingForm class to parse the form data. This class has an on() method which allows us to specify a callback function when a file is uploaded. The callback function is passed an error object and a fields object which contains the form fields and their values. We can also access the uploaded file data, such as its size, name, and data, by accessing the files array.


const formidable = require('formidable');
const fs = require('fs');

// Create an incoming form object
let form = new formidable.IncomingForm();

// Specify that we want to allow the user to upload multiple files in a single request
form.multiples = true;

// Store all uploads in the /uploads directory
form.uploadDir = path.join(__dirname, '/uploads');

// Every time a file has been uploaded successfully,
// rename it to it's orignal name
form.on('file', function(field, file) {
	fs.rename(file.path, path.join(form.uploadDir, file.name));
});

// Parse the incoming request containing the form data
form.parse(req, function(err, fields, files) {
	// Read the file data
	let data = fs.readFileSync(files.filetoupload.path);
	// Do something with the file data
});

The above code creates an IncomingForm object and specifies that it should accept multiple files. It also sets the upload directory as the /uploads directory. When a file is uploaded, it is renamed to its original name. The code then parses the form data and the file data is read from the files array. The readFileSync() method is used to read the file data, which is then stored in the data variable.

Once the file data is stored in the data variable, it can be used for whatever purpose required. For example, it could be written to a database, stored in memory, or sent to another service via an API call.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe