Mern Exp-14
Mern Exp-14
POST-LAB:
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);
});
```
```javascript
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File contents:', data);
} catch (err) {
console.error('Error:', err);
}
```
```javascript
const fs = require('fs');
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;
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.
// 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));
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');
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
if (!image) {
console.log('Image not found in the database');
return;
}