Created
March 25, 2024 17:37
-
-
Save abhinavjonnada82/c7f7b85b406c27a01bd9e9b9c0f3f6a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
// Reading a file | |
fs.readFile('file.txt', 'utf8', (err, data) => { | |
if (err) { | |
console.error('Error reading file:', err); | |
} else { | |
console.log('File content:', data); | |
} | |
}); | |
// Writing to a file | |
const contentToWrite = 'This is some content to write to the file.'; | |
fs.writeFile('output.txt', contentToWrite, 'utf8', (err) => { | |
if (err) { | |
console.error('Error writing to file:', err); | |
} else { | |
console.log('File has been written successfully.'); | |
} | |
}); | |
// Create a http server | |
const http = require('http'); | |
const server = http.createServer((req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
res.end('Hello, Node.js!'); | |
}); | |
const port = 3000; | |
server.listen(port, () => { | |
console.log(`Server is running on http://localhost:${port}`); | |
}); | |
// Create an express server & middleware | |
const express = require('express'); | |
const app = express(); | |
// Logger Middleware | |
app.use((req, res, next) => { | |
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); | |
next(); | |
}); | |
// Body Parser Middleware | |
app.use(express.json()); | |
// Route Handler | |
app.get('/', (req, res) => { | |
res.send('Hello, Express!'); | |
}); | |
// Error Handling Middleware | |
app.use((err, req, res, next) => { | |
console.error(err.stack); | |
res.status(500).send('Something went wrong!'); | |
}); | |
const port = 3000; | |
app.listen(port, () => { | |
console.log(`Server is running on http://localhost:${port}`); | |
}); | |
// GET request - AXIOS | |
const axios = require('axios'); | |
axios.get('https://api.example.com/data') | |
.then(response => { | |
console.log('API response:', response.data); | |
}) | |
.catch(error => { | |
console.error('Error fetching data:', error); | |
}); | |
// Promises | |
const fs = require('fs'); | |
function readFileAsync(filePath) { | |
return new Promise((resolve, reject) => { | |
fs.readFile(filePath, 'utf8', (err, data) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(data); | |
} | |
}); | |
}); | |
} | |
const fs = require('fs').promises; | |
async function readFileAsync(file) { | |
try { | |
const data = await fs.readFile(file, 'utf8'); | |
console.log('File contents:', data); | |
} catch (err) { | |
console.error('Error:', err.message); | |
} | |
} | |
readFileAsync('nonExistentFile.txt'); | |
// Streams | |
const fs = require('fs'); | |
// read stream | |
const readableStream = fs.createReadStream('largefile.txt', 'utf8'); | |
readableStream.on('data', chunk => { | |
console.log('Received a chunk of data:', chunk); | |
}); | |
// websocket | |
const WebSocket = require('ws'); | |
const wss = new WebSocket.Server({ port: 8080 }); | |
// Event handler for new connections | |
wss.on('connection', (ws) => { | |
console.log('New client connected.'); | |
// Event handler for receiving messages from clients | |
ws.on('message', (message) => { | |
console.log('Received message:', message); | |
// Send a response back to the client | |
ws.send(`Server received: ${message}`); | |
}); | |
// Event handler for client disconnection | |
ws.on('close', () => { | |
console.log('Client disconnected.'); | |
}); | |
}); | |
readableStream.on('end', () => { | |
console.log('Reading finished.'); | |
}); | |
readableStream.on('error', err => { | |
console.error('Error while reading:', err); | |
}); | |
// write stream | |
const writableStream = fs.createWriteStream('outputFile.txt'); | |
writableStream.write('This is the first line.n'); | |
writableStream.write('This is the second line.n'); | |
writableStream.end('Writing data completed.'); | |
// Authentication & Authorization | |
const express = require('express'); | |
const jwt = require('jsonwebtoken'); | |
const app = express(); | |
const secretKey = 'your-secret-key'; | |
// Middleware to check for authentication token | |
function authenticateToken(req, res, next) { | |
const token = req.header('Authorization')?.split(' ')[1]; | |
if (!token) { | |
return res.sendStatus(401); | |
} | |
jwt.verify(token, secretKey, (err, user) => { | |
if (err) { | |
return res.sendStatus(403); | |
} | |
req.user = user; | |
next(); | |
}); | |
} | |
// Login route | |
app.post('/login', (req, res) => { | |
// Assuming you have a user authentication logic here | |
const user = { id: 1, username: 'exampleUser' }; | |
const token = jwt.sign(user, secretKey); | |
res.json({ token }); | |
}); | |
// Protected route | |
app.get('/protected', authenticateToken, (req, res) => { | |
res.json({ message: 'Protected route accessed!', user: req.user }); | |
}); | |
app.listen(3000, () => { | |
console.log('Server is running on http://localhost:3000'); | |
}); | |
// multiple http requests | |
const urls = ['https://api.example.com/data1', 'https://api.example.com/data2']; | |
Promise.all( | |
urls.map((url) => fetch(url).then((response) => response.json())) | |
) | |
.then((data) => { | |
console.log('Data from all URLs:', data); | |
}) | |
.catch((error) => { | |
console.error('Error fetching data:', error); | |
}); | |
// mongoose | |
const express = require('express') | |
const mongoose = require('mongoose') | |
const bodyParser = require('body-parser') | |
const app = express() | |
const port = process.env.port || 3000; | |
app.use(bodyParser.json()); | |
mongoose.connect('mongodb://localhost:27017/my_database', { | |
useNewUrlParser: true, | |
useUnifiedTopology: true | |
}) | |
const db = mongoose.connection; | |
db.on('error', () => { | |
console.log('error') | |
}) | |
db.once('open', () => { | |
console.log('connected') | |
}) | |
const itemSchema = new mongoose.Schema({ | |
name: String, | |
description: String | |
}) | |
const Item = mongoose.model('Item', itemSchema); | |
app.get('/items', async (req, res) => { | |
try{ | |
const items = await Item.find(); | |
res.json(items); | |
} | |
catch (error) { | |
res.status(500).json({ message: error.message }); | |
} | |
}) | |
app.get('/items/:id', async (req, res) => { | |
try { | |
const item = await Item.findById(req.params.id); | |
if (!items) { | |
return res.status(404).json({ message: 'Item not found!'}) | |
} | |
res.json(item) | |
} | |
catch (error) { | |
res.status(500).json({ message: error.message }); | |
} | |
}) | |
app.post('/items', async (req, res) => { | |
try { | |
const newItem = Item(req.body); | |
const savedItem = await newItem.save(); | |
res.status(201).json(savedItem) | |
} | |
catch { | |
res.status(400).json({ message: error.message }) | |
} | |
}) | |
app.put('/items/:id', async (req, res) => { | |
try { | |
const updatedItem = await Item.findByIdAndUpdate(req.params.id); | |
if (!updatedItem) { | |
return res.status(404).json({ message: 'Item not found!'}) | |
} | |
res.json(updatedItem); | |
} | |
catch (error) { | |
res.status(500).json({ message: error.message }); | |
} | |
}) | |
app.delete('/items/:id', async (req, res) => { | |
try { | |
const deletedItem = await Item.findByIdAndDelete(req.params.id) | |
if (!deletedItem) { | |
return res.status(404).json({ message: 'Item deleted!'}) | |
} | |
res.json({ messagge: 'deletedItem' }); | |
} | |
catch (error) { | |
res.status(500).json({ message: error.message }); | |
} | |
}) | |
app.listen(port, () => { | |
console.log(`Server starting on port ${port}`) | |
}) | |
const nock = require('nock'); | |
const { describe } = require('node:test'); | |
describe('user module', () => { | |
test('fetch data', async () => { | |
const uId = 123; | |
const expectedUserData = { name: 'John Doe', email: '[email protected]' }; | |
nock('https://api.example.com') | |
.get(`/users/${uId}`) | |
.reply(200, JSON.stringify(expectedUserData)) | |
const userD = await getUserData(uId); | |
expect(userD).toEqual(expectedUserData) | |
nock.cleanAll(); | |
}) | |
test('handles error', async () => { | |
const uId = 123; | |
nock('https://api.example.com') | |
.get(`/users/${uId}`) | |
.reply(500); | |
await expect(getUserData(uId)).rejects.toThrowError(); | |
nock.cleanAll(); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment