-
Notifications
You must be signed in to change notification settings - Fork 0
/
race-condition.js
55 lines (42 loc) · 1.53 KB
/
race-condition.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const app = express();
const exportFilePath = path.join(__dirname, 'export.txt');
// Hardcoded data for user 1 and user 2
const userDataMap = {
'1': 'User 1: John Doe, Balance: $1000\n',
'2': 'User 2: Jane Smith, Balance: $1500\n'
};
app.get('/export', async (req, res) => {
const userId = req.query.user;
const userData = userDataMap[userId] || 'Unknown User\n';
try {
// Step 1: Write user data to the file
await fs.writeFile(exportFilePath, userData);
// Simulate processing delay
await new Promise(resolve => setTimeout(resolve, 3000));
// Step 2: Read the file content (which should be the user's data)
const fileContent = await fs.readFile(exportFilePath, 'utf8');
await fs.unlink(exportFilePath)
res.send(`Exported data: ${fileContent}`);
} catch (err) {
res.status(500).send('Error exporting data');
}
});
/*
http://localhost:3000/export?user=1
http://localhost:3000/export?user=2
If both requests are made nearly simultaneously, both endpoints gets user=2 information
*/
app.listen(3000, () => {
console.log('Server running on port 3000');
});
/*FIX
Create random and unique name for each files
const exportFilePath = path.join(__dirname, `export_${userId}.txt`);
or
const crypto = require('crypto');
const randomString = crypto.randomBytes(6).toString('hex');
const exportFilePath = path.join(__dirname, `export_${randomString}.txt`);
*/