Here's a simple Node.js application that allows you to store dream journal entries in a JSON file and serves a basic web page to interact with the data. We'll use Express for the web server and body-parser to parse incoming request bodies.
First, initialize your project and install dependencies:
bash Copy code
mkdir dream-journal
cd dream-journal
npm init -y
npm install express body-parser
Create an index.js file for the server:
javascript Copy code
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs-extra');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Read existing data or initialize as empty array
let data = [];
try {
data = await fs.readJson('data.json');
} catch (err) {
if (err.code !== 'ENOENT') throw err;
}
// GET all entries
app.get('/api/entries', (req, res) => {
res.json(data);
});
// POST a new entry
app.post('/api/entries', async (req, res) => {
const newEntry = req.body;
data.push(newEntry);
await fs.writeJson('data.json', data);
res.status(201).json(newEntry);
});
// PUT (update) an entry
app.put('/api/entries/:id', async (req, res) => {
const index = data.findIndex((entry) => entry.id === parseInt(req.params.id));
if (index === -1) return res.status(404).send('Entry not found');
data[index] = { ...data[index], ...req.body };
await fs.writeJson('data.json', data);
res.json(data[index]);
});
// DELETE an entry
app.delete('/api/entries/:id', async (req, res) => {
const index = data.findIndex((entry) => entry.id === parseInt(req.params.id));
if (index === -1) return res.status(404).send('Entry not found');
data.splice(index, 1);
await fs.writeJson('data.json', data);
res.sendStatus(204);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Create a basic web page index.html in a new folder named public:
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dream Journal</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid black; padding: 8px; text-align: left; }
</style>
</head>
<body>
<h1>Dream Journal</h1>
<form id="entry-form">
<label for="date">Date:</label>
<input type="date" name="date" required><br>
<label for="content">Dream:</label>
<textarea name="content" rows="4" required></textarea><br>
<button type="submit">Save Dream</button>
</form>
<table id="entries-table">
<thead>
<tr>
<th>Date</th>
<th>Dream</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const form = document.getElementById('entry-form');
const tableBody = document.querySelector('#entries-table tbody');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(form);
const entry = Object.fromEntries(formData);
entry.id = Date.now();
const response = await fetch('/api/entries', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(entry),
});
if (response.ok) {
const newEntry = await response.json();
addEntryToTable(newEntry);
form.reset();
}
});
async function fetchEntries() {
const response = await fetch('/api/entries');
const entries = await response.json();
entries.forEach(addEntryToTable);
}
function addEntryToTable(entry) {
const row = document.createElement('tr');
row.innerHTML = `
<td>${entry.date}</td>
<td>${entry.content}</td>
<td>
<button onclick="editEntry(${entry.id})">Edit</button>
<button onclick="deleteEntry(${entry.id})">Delete</button>
</td>
`;
tableBody.appendChild(row);
}
async function editEntry(id) {
const response = await fetch(`/api/entries/${id}`);
const entry = await response.json();
form.date.value = entry.date;
form.content.value = entry.content;
form.id.value = entry.id;
}
async function deleteEntry(id) {
await fetch(`/api/entries/${id}`, { method: 'DELETE' });
tableBody.innerHTML = '';
fetchEntries();
}
fetchEntries();
</script>
</body>
</html>
Update the index.js file to serve the index.html file:
javascript Copy code
// ...
app.use(express.static('public'));
// ...
Start the server:
bash Copy code
node index.js
Now, you can access the dream journal web page at http://localhost:3000. The data will be stored in a JSON file named data.json.