InterviewSolution
| 1. |
How to upload a file using formidable in Express.js? |
|
Answer» Formidable is an easy-to-use NPM module, which is used to parse from data, especially when uploading files in an Express JS app. It is very popular and has got nearly half a million downloads on NPM. We will learn how to use it next. First create a new directory and change it. After that initialize a Node.js app by the npm init -y command. We are also adding the dependencies of express and formidable in it. Then, create a file index.js in the root directory. Also create an uploads folder in the root directory, in which we are going to store the uploaded files. Next, we are first importing express and after that the fs (File System) module. We are also importing PATH modules and formidable. We are using the app with express and with it creating a POST route using app.post(). Inside the post method, we are TAKING the data from the incoming form using formidable. Now, we are PARSING the form and adding the incoming file to the uploads folder. We are also reading it using the fs module. Lastly, we are listening at port 3000 for incoming requests. Now, go to POSTMAN and create a POST request and MAKE a key of profilePic and upload a file and send it. Now, when we check in the uploads folder the file is uploaded successfully in our server. |
|