Last active
January 15, 2022 01:13
-
-
Save diegofcornejo/1b4fbb4f2b7686866491fd35ce61f526 to your computer and use it in GitHub Desktop.
NodeJS - Express get files in folder and read file content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express'); | |
| const app = express(); | |
| const port = 8844; | |
| const fs = require('fs').promises; | |
| const getFiles = (path) => { | |
| return fs.readdir(path); | |
| } | |
| const generateRoom = async (path, file) => { | |
| file = `${path}/${file}`; | |
| const { ino, ctime } = await fs.stat(file); | |
| let room = { | |
| recid: ino, | |
| file: file.split("/")[2], | |
| date: ctime | |
| } | |
| const roomInfo = await getRoomInfo(file); | |
| room.player = roomInfo.player ? roomInfo.player[0] : 'Unknow Player'; | |
| room.ip = roomInfo.ip ? roomInfo.ip[0] : 'Unknow IP'; | |
| return room; | |
| } | |
| const getRoomInfo = async (file) => { | |
| const lineReader = require('readline').createInterface({ | |
| input: require('fs').createReadStream(file) | |
| }); | |
| let counter = 0; | |
| let player, ip; | |
| for await (let line of lineReader) { | |
| counter++ | |
| if (counter == 2) { | |
| player = line.match(/(?<== ).*(?=[(])/g); | |
| ip = line.match(/(?<=f:).*(?=[)])/g); | |
| lineReader.close(); | |
| break; | |
| } | |
| } | |
| return { player, ip }; | |
| } | |
| const getRooms = async () => { | |
| const roomlogs = './room-logs'; | |
| const rooms = []; | |
| const logs = await getFiles(roomlogs); | |
| for await (const log of logs) { | |
| const room = await generateRoom(roomlogs, log); | |
| rooms.push(room); | |
| } | |
| return rooms; | |
| } | |
| const login = (user, password) => { | |
| const users = require('./users.json') | |
| return users.hasOwnProperty(user) && users[user].password == password; | |
| } | |
| app.get('/rooms', (req, res) => { | |
| const { user, password } = req.query; | |
| if (login(user, password)) { | |
| (async () => { | |
| res.status(200).json(await getRooms()); | |
| })(); | |
| } else { | |
| res.status(401).send('Unauthorized') | |
| } | |
| }) | |
| app.listen(port, () => { | |
| console.log(`Example app listening at http://localhost:${port}`) | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "randomtechguy":{ | |
| "password":"password", | |
| "role":"admin" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment