|
1 | | -import fs from 'fs'; |
| 1 | +import fs from 'fs/promises'; |
2 | 2 |
|
3 | 3 | const filePath = './src/backend/.env'; |
4 | 4 | const lineToAdd = 'DATABASE_URL="postgresql://postgres:docker@localhost:5432/nerpm?schema=public"'; |
5 | 5 |
|
6 | | -if (!fs.existsSync(filePath)) { |
7 | | - fs.writeFileSync(filePath, lineToAdd, 'utf8'); |
8 | | - return; |
9 | | -} |
10 | | - |
11 | | -fs.readFile(filePath, 'utf8', (err, data) => { |
12 | | - if (err) { |
13 | | - console.error('Error reading file:', err); |
| 6 | +async function setupDatabase() { |
| 7 | + // Check if file exists |
| 8 | + try { |
| 9 | + await fs.access(filePath); |
| 10 | + } catch { |
| 11 | + // File doesn't exist, create it with the DATABASE_URL |
| 12 | + await fs.writeFile(filePath, lineToAdd, 'utf8'); |
| 13 | + console.log('Created .env file with DATABASE_URL'); |
14 | 14 | return; |
15 | 15 | } |
16 | 16 |
|
17 | | - // Split file contents into lines |
| 17 | + // File exists, read its contents |
| 18 | + const data = await fs.readFile(filePath, 'utf8'); |
18 | 19 | const lines = data.trim().split('\n'); |
19 | 20 |
|
| 21 | + // Check if DATABASE_URL already exists |
20 | 22 | for (const line of lines) { |
21 | | - //db url already exists, no need to add it |
22 | | - if (line.startsWith('DATABASE_URL=')) return; |
23 | | - } |
24 | | - |
25 | | - fs.appendFile(filePath, `\n${lineToAdd}`, 'utf8', (err) => { |
26 | | - if (err) { |
27 | | - console.error('Error appending line to file:', err); |
| 23 | + if (line.startsWith('DATABASE_URL=')) { |
| 24 | + console.log('DATABASE_URL already exists in .env file'); |
28 | 25 | return; |
29 | 26 | } |
30 | | - }); |
31 | | -}); |
| 27 | + } |
| 28 | + |
| 29 | + // DATABASE_URL doesn't exist, append it |
| 30 | + await fs.appendFile(filePath, `\n${lineToAdd}`, 'utf8'); |
| 31 | + console.log('Added DATABASE_URL to existing .env file'); |
| 32 | +} |
| 33 | + |
| 34 | +await setupDatabase(); |
0 commit comments