Node.js File Uploads are done using pre-defined module. In Node.js for every implementation we use the modules. There are many modules for different purposes.

For File Upload we use Formidable module in Node.js. Below are the steps to upload a file using node.js

  • File uploads are done using module called “Formidable”.
  • The Formidable module can be downloaded and installed using NPM:
  • npm install formidable
  • Node.js and formidable module needs to be installed to upload files .

Let us understand this with the help of an example. Below is the example to create a file upload form in node.js

  1. Create index.js file and implement the formidable code inside that
  2. var formidable=require(‘formidable’); // This is the main module that is required
  3. var http= require(‘http’);     // http module is used to create server
  4. http.createServer(function(req,res)
  5. {
  6. res.writeHead(200, {‘Content-Type’: ‘text/html’});
  7. res.write(‘<form action=”fileupload” method=”post” enctype=”multipart/form-data”>’);
  8. res.write(‘<input type=”file” name=”filetoupload”><br>’);
  9. res.write(‘<input type=”submit”>’);
  10. res.write(‘</form>’);
  11. return res.end();
  12. });


Now create another file that will upload the file. The above file only creates the form that user will use to upload the file. Below is the fileupload.js code :

var http = require(‘http’);
var formidable = require(‘formidable’);

http.createServer(function (req, res) {
  if (req.url == ‘/fileupload‘) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write(‘File uploaded’);
  } ).listen(8081);

244total visits,1visits today