0% found this document useful (0 votes)
25 views11 pages

Mern Exp-14

1. Middleware in Node.js are functions that process HTTP requests and responses as they pass through an application, allowing tasks like request parsing, authentication, and error handling. Express.js uses middleware extensively for routing and web development tasks. 2. Multer is middleware used for handling file uploads in Node.js applications. It simplifies receiving and storing files uploaded by users. 3. The fs module allows reading, writing, updating, deleting, and manipulating files and directories in Node.js.

Uploaded by

Preethi Sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views11 pages

Mern Exp-14

1. Middleware in Node.js are functions that process HTTP requests and responses as they pass through an application, allowing tasks like request parsing, authentication, and error handling. Express.js uses middleware extensively for routing and web development tasks. 2. Multer is middleware used for handling file uploads in Node.js applications. It simplifies receiving and storing files uploaded by users. 3. The fs module allows reading, writing, updating, deleting, and manipulating files and directories in Node.js.

Uploaded by

Preethi Sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

MSWD EXP-14

POST-LAB:

1. Explain the concept of middleware in the context of Node.js.


In Node.js, middleware are functions that process and modify HTTP requests
and responses as they pass through an application. They allow tasks like request
parsing, authentication, and error handling, making code modular and promoting
clean, organized development. Express.js, a popular Node.js web framework,
extensively uses middleware for routing and various web development tasks.

2. What is Multer and what is its purpose in Node.js.


Multer is a Node.js middleware used for handling multipart/form-data, which is
typically used for uploading files in web applications. Its purpose is to simplify the
process of receiving and storing files uploaded by users. It works seamlessly with
Express.js and provides a way to handle file uploads, making it easier to manage and
process user-generated content like images, documents, and more.

3. What is the purpose of the fs module in Node.js?


The `fs` module in Node.js stands for "file system" and is used to interact with
the file system of the underlying operating system. Its purpose is to perform various
file operations, such as reading, writing, updating, deleting, and manipulating files
and directories.

4. How do you read the contents of a file using the fs module in Node.js?
To read the contents of a file using the `fs` module in Node.js:

1. Asynchronously: Use `fs.readFile` with a callback to read the file's contents without
blocking the event loop.

```javascript
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('File contents:', data);
});
```

2. Synchronously (not recommended for performance-critical apps): Use `fs.readFileSync` to


read the file's contents in a blocking manner.

```javascript
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File contents:', data);
} catch (err) {
console.error('Error:', err);
}
```

Replace `'example.txt'` with the file path you want to read.

5. How do you write data to a file using the fs module in Node.js?


To write data to a file using the `fs` module in Node.js, you can use the `fs.writeFile`
method. Here's how to do it:

```javascript
const fs = require('fs');

// Specify the file path and data to write


const filePath = 'example.txt';
const dataToWrite = 'This is the data to write to the file.';

fs.writeFile(filePath, dataToWrite, (err) => {


if (err) {
console.error('Error writing to the file:', err);
return;
}
console.log('Data has been written to the file.');
});
```

In this code:

1. Replace `'example.txt'` with the path to the file you want to write data to.

2. `dataToWrite` should contain the data you want to write to the file.

3. The `fs.writeFile` method is used with a callback function to handle any errors during the
writing process.

This code writes the specified data to the file, creating the file if it doesn't exist or
overwriting its content if it does.

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.

const fs = require('fs');
const http = require('http');
const path = require('path');
const port = 3000;

const publicFolder = path.join(__dirname, 'public');


const filePath = path.join(publicFolder, 'example.txt');
// Create a Node.js server
const server = http.createServer((req, res) => {
if (req.url === '/') {
// Read data from the file
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found.');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`File Contents:<br>${data}`);
}
});
} else if (req.url === '/append') {
// Append new text to the file
const textToAppend = '\nThis is some new text.';
fs.appendFile(filePath, textToAppend, (err) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error appending data to the file.');
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Data appended to the file.');
}
});
} else if (req.url === '/delete') {
// Delete the file
fs.unlink(filePath, (err) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error deleting the file.');
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('File deleted.');
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});

// Create the 'public' directory if it doesn't exist


if (!fs.existsSync(publicFolder)) {
fs.mkdirSync(publicFolder);
}

// Create the 'example.txt' file if it doesn't exist


if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, 'Initial text in the file.');
}

server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
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.

const express = require('express');


const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path');
const Image = require('./models/Image'); // Your Mongoose Image model

const app = express();


const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));

// Configure Multer for file uploads


const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Set the destination folder for uploaded files
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // Define file naming
}
});

const upload = multer({ storage });

// Define the Image model/schema


// const Image = mongoose.model('Image', yourImageSchema);

// Create a POST route for image uploads


app.post('/upload', upload.single('image'), (req, res) => {
// Handle the image upload and save details to the database
const { originalname, filename } = req.file;
const newImage = new Image({
name: originalname,
path: filename,
// Add other image-related data
});
newImage.save()
.then(image => res.json({ message: 'Image uploaded and saved to the database', image }))
.catch(err => res.status(500).json({ error: err.message }));
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Post-Lab:
Question 1: Display the contents of other file types(pdf) to the browser by GET route of
the server.
const express = require('express');
const path = require('path');

const app = express();


const port = 3000;

// Configure static file serving


app.use(express.static(path.join(__dirname, 'pdfs')));

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Question 2: Check the file uploaded in to your database properly or not. Check the file
format in thedatabase.
const mongoose = require('mongoose');
const Image = require('./models/Image'); // Your Mongoose Image model

// Connect to MongoDB (if not already connected)


mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true,
useUnifiedTopology: true });

// Find the image in the database (replace with your criteria)


const imageId = 'your-image-id'; // Replace with the actual ID or criteria
Image.findById(imageId, (err, image) => {
if (err) {
console.error('Error:', err);
return;
}

if (!image) {
console.log('Image not found in the database');
return;
}

// Check the file format based on the file name


const fileName = image.name;
const fileFormat = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();

console.log('File Format:', fileFormat);


});

// Close the database connection when done (optional)


// mongoose.connection.close();

You might also like