CSV2HTML/backend/index.js

120 lines
2.6 KiB
JavaScript
Raw Normal View History

2021-10-30 23:36:07 +08:00
const path = "./csv";
const data = {};
const column = {};
let files = [];
const fs = require("fs");
const papa = require("papaparse");
const chokidar = require("chokidar");
chokidar.watch(path).on("all", () => {
console.log("File changed. Reloading ...");
files = fs.readdirSync(`${path}`).filter((file) => file.endsWith(".csv"));
for (const file of files) {
const csv = fs.readFileSync(`${path}/${file}`, {
encoding: "utf8",
});
const parsed = papa.parse(csv, {
skipEmptyLines: true,
}).data;
const header = parsed[0];
column[file] = [];
for (const h of header) {
column[file].push({
key: h,
text: h,
sorting: "",
});
}
const converted = [];
for (let j = 1; j < parsed.length; ++j) {
const d = parsed[j];
const e = {};
for (let i = 0; i < d.length; ++i) {
e[header[i]] = d[i];
}
converted.push(e);
}
data[file] = converted;
}
});
const express = require("express");
const app = express();
const cors = require("cors");
app.use(cors());
const port = 3000;
app.get("/files", (_, res) => {
res.send(files);
});
function compare(a, b) {
const m = a - b;
if (isNaN(m)) {
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
}
return m;
}
app.get("/csv/:file", (req, res) => {
const {
file
} = req.params;
const raw = data[file];
const col = column[file];
let processed = raw;
let query_key = "";
let key = "";
const c = col.find((ele) => {
key = ele.key;
query_key = `sort_${key}`;
return query_key in req.query;
});
if (!(c === "undefined")) {
processed = [...raw];
if (req.query[query_key] == "ASC") {
processed.sort((a, b) => compare(a[key], b[key]));
} else {
processed.sort((a, b) => compare(b[key], a[key]));
}
}
if ("pSize" in req.query && "cPage" in req.query) {
const size = req.query.pSize;
const page = req.query.cPage;
processed = processed.slice((page - 1) * size, page * size);
}
res.send({
totals: raw.length,
data: processed,
});
});
app.use(express.static("public"));
app.get("/column/:file", (req, res) => {
const {
file
} = req.params;
res.send(column[file]);
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
});