Files: e7a281942d7ba07122d3b8d738ef13d3b128ea0e / nodejs-assets / nodejs-project / main.js
1506 bytesRaw
1 | const rn_bridge = require('rn-bridge') |
2 | const express = require('express') |
3 | const bodyParser = require('body-parser') |
4 | |
5 | const Dat = require('dat-node') |
6 | const fs = require('fs') |
7 | const { join } = require('path') |
8 | |
9 | const PORT = 8182 |
10 | let datPath = '' |
11 | |
12 | const downloadDat = key => { |
13 | return new Promise((resolve, reject) => { |
14 | const path = join(datPath, key) |
15 | |
16 | if (!fs.existsSync(path)) { |
17 | fs.mkdirSync(path) |
18 | } |
19 | |
20 | Dat(path, { |
21 | key, |
22 | sparse: true |
23 | }, async (err, dat) => { |
24 | if (err) { |
25 | return reject(err) |
26 | } |
27 | |
28 | dat.joinNetwork(err => { |
29 | dat.archive.readdir('/', (err, files) => { |
30 | if (err) { |
31 | return reject(err) |
32 | } |
33 | |
34 | return resolve(files) |
35 | }) |
36 | }) |
37 | }) |
38 | }) |
39 | } |
40 | |
41 | const server = express() |
42 | server.use(bodyParser.json()) |
43 | |
44 | server.post('/setPath', (req, res) => { |
45 | const { path } = req.body |
46 | datPath = path |
47 | |
48 | res.send(200) |
49 | res.end() |
50 | }) |
51 | |
52 | server.post('/download/:key', async (req, res) => { |
53 | const { key } = req.params |
54 | |
55 | try { |
56 | const files = await downloadDat(key) |
57 | res.json(files) |
58 | } catch (err) { |
59 | res.send(err) |
60 | } |
61 | |
62 | res.end() |
63 | }) |
64 | |
65 | server.get('/files/:key', (req, res) => { |
66 | const { key } = req.params |
67 | |
68 | const files = fs.readdirSync(join(datPath, key)) |
69 | |
70 | res.json(files) |
71 | res.end() |
72 | }) |
73 | |
74 | server.listen(PORT, () => { |
75 | |
76 | // Inform react-native node is initialized. |
77 | rn_bridge.channel.send(`Node was initialized.`) |
78 | }) |
79 |
Built with git-ssb-web