Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

MERN (ADV) EXP 14

NAME : K.HARSHAVARDHAN

SEC : 33-B

ID : 2200031420

14. Node JS working with Files


Aim/Objective: The objective of this experiment is to be familiar with file operations through NodeJS
server routes and uploading files to the MongoDB Database.
Description:
Working with files in Node.js involves reading from and writing to files on the file system. Use the fs
module (built-in module in Node.js) in this regard.
Reading Files:
• Use the fs.readFile() method to read the contents of a file asynchronously
Writing Files:
• Use the fs.writeFile() method to write data to a file asynchronously
Appending to Files:
• Use the fs.appendFile() method
Deleting Files:
• Use the fs.unlink() method
Provide the file path and a callback function to handle the file data and handling errors.
Uploading Files to database
• Use the multer package which is a popular middleware for handling file uploads in Node.js.
Pre-Requisites:
Node js, Web Browsers, express, Postman, nodemon, dotenv, fs
>npm install multer
In-Lab:

Exercise 1: Create a Node.js server. Create a .txt file within public folder. Access the file for reading
data from it and writing data into the file. Append some new texts in the file after that delete the file.

Exercise 2: Create a Node.js server and connect your database. Using mongoose create an image
model (schema) that contains information about your image file. Configure the storage using multer
for the image file. Create upload middleware instance using multer to handle file upload requests.
Attach the middleware to the post route(s) or endpoint(s) in your Node.js application.

Procedure/Program:
OUTPUT:
Post-Lab:

Question 1: Display the contents of other file types(pdf) to the browser by GET route of the server.

Question 2: Check the file uploaded in to your database p


roperly or not. Check the file format in the
database.

Procedure/Program:
OUTPUT:

You might also like