Home » Node.js

Node.js Formidable Module-1

In this article, we are going to learn about Node.js formidable module with an example of selecting a file and submitting to server.
Submitted by Manu Jemini, on November 20, 2017

Every time we’ve worked on a form in a website, the most complex part is to parse form data and to upload file on the server. But here in Node.js, it provides us a module known as formidable which was developed for Transloadit, a service basically focusing on uploading images and videos. Formidable is not a high-level package, so if we are using express.js framework we shall not need to include it.

Note: We can also use express-formidable, which comes with express framework of node.js

To install formidable package we just need to type a 'cmd' command: npm i –S formidable

Now we are going to see a basic example of formidable by creating a file input and a submit button, we wrap them in a form with method post and enctype multipart/form-data we write all these on our browser screen by using .writeHead and .write methods which we have already discussed in article: How do I read a file in Node.js using readFile?

Server File

//step 1
var formidable = require('formidable');
//step 2
var http = require('http');
//step 3
http.createServer(function (req, res) {
//step 4
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
  res.write('<input type="file" name="filetoupload"><br>');
  res.write('<input type="submit">');
  res.write('</form>');
  return res.end();
//step 5
}).listen(8080);

Discussion on steps we have followed in our server file,

  • We need to require formidable module from node modules and store its reference in variable formidable.
  • We store an http in local variable http.
  • Then we create a http server by using .createServer() method.
  • After that, create a form and display in on browser screen by using .write() method.
  • And finally, the server listens on port 8080.

To run server file, you just need to save it by a random name and then open 'cmd', type node, and file name.

formidable module 1 example

Next: Node.js Formidable Module-2

Happy coding...



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.