64 lines
1.8 KiB
JavaScript
64 lines
1.8 KiB
JavaScript
const express = require('express');
|
|
const bodyParser = require('body-parser');
|
|
const xlsx = require('xlsx');
|
|
const fs = require('fs');
|
|
const { exec } = require('child_process');
|
|
const app = express();
|
|
const port = 3000;
|
|
const filePath = './data/todos.xlsx';
|
|
|
|
app.use(bodyParser.json());
|
|
app.use(express.static('public'));
|
|
|
|
function readTodos() {
|
|
if (fs.existsSync(filePath)) {
|
|
const workbook = xlsx.readFile(filePath);
|
|
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
|
return xlsx.utils.sheet_to_json(sheet);
|
|
} else {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function writeTodos(todos) {
|
|
const worksheet = xlsx.utils.json_to_sheet(todos);
|
|
const workbook = xlsx.utils.book_new();
|
|
xlsx.utils.book_append_sheet(workbook, worksheet, 'Todos');
|
|
xlsx.writeFile(workbook, filePath);
|
|
}
|
|
|
|
app.get('/todos', (req, res) => {
|
|
const todos = readTodos();
|
|
res.json({ data: todos });
|
|
});
|
|
|
|
app.post('/todos', (req, res) => {
|
|
const todos = readTodos();
|
|
const task = req.body.task;
|
|
const newTodo = { id: todos.length ? todos[todos.length - 1].id + 1 : 1, task: task };
|
|
todos.push(newTodo);
|
|
writeTodos(todos);
|
|
res.json({ data: newTodo });
|
|
});
|
|
|
|
app.delete('/todos/:id', (req, res) => {
|
|
const todos = readTodos();
|
|
const updatedTodos = todos.filter(todo => todo.id != req.params.id);
|
|
writeTodos(updatedTodos);
|
|
res.json({ message: "success" });
|
|
});
|
|
|
|
app.get('/count-a', (req, res) => {
|
|
const todos = readTodos();
|
|
const allTasks = todos.map(todo => todo.task).join('\n');
|
|
fs.writeFileSync('tasks.txt', allTasks);
|
|
exec('awk -f count_a.awk tasks.txt', (error, stdout) => {
|
|
res.json({ count: parseInt(stdout.trim(), 10) });
|
|
});
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server is running on port ${port}`);
|
|
});
|
|
|