Skip to content

Instantly share code, notes, and snippets.

@fselcukcan
Created May 25, 2019 19:58
Show Gist options
  • Select an option

  • Save fselcukcan/13d44f8edc9cc74b05571f9d478a1c15 to your computer and use it in GitHub Desktop.

Select an option

Save fselcukcan/13d44f8edc9cc74b05571f9d478a1c15 to your computer and use it in GitHub Desktop.

Revisions

  1. fselcukcan created this gist May 25, 2019.
    82 changes: 82 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,82 @@
    'use strict';

    const Hapi = require('@hapi/hapi');
    const util = require('util');
    const fs = require("fs");

    const readFile = util.promisify(fs.readFile);
    const writeFile = util.promisify(fs.writeFile);

    function bootstrap_db () {
    let db_hash_data = fs.readFileSync("db_hash.json");
    let db_hash = JSON.parse(db_hash_data);
    console.log("db_hash: ", db_hash);

    // consistency
    /*
    let files = fs.readdirSync("files");
    let diff = files.filter(file => !db_hash.map(x => x.path).includes(file))
    diff.map(path => ({"filename": path, "path": path}));
    db_hash.push(diff);
    fs.writeFileSync("db_hash.json", db_hash);
    */
    return db_hash;
    }
    let db_hash = bootstrap_db()
    console.log("global db_hash", db_hash)

    async function save (db_hash, data) {
    db_hash.push(data);
    let result = await writeFile("db_hash.json", JSON.stringify(db_hash));
    console.log("global2 db_hash", db_hash)
    }

    const init = async () => {

    const server = Hapi.server({
    port: 3001,
    host: 'localhost'
    });

    server.route({
    method: 'GET',
    path:'/',
    handler: (request, h) => {

    return h.file("index.html");
    }
    });

    server.route({
    method: 'POST',
    path:'/save_file',
    handler: (request, h) => {

    let { filename, path } = request.payload["my-file"];
    let path_arr = path.split("/");
    path = path_arr[path_arr.length - 1];
    save(db_hash, { filename, path });
    return { path, filename };
    },
    options: {
    payload: {
    output: "file",
    uploads: "files",
    maxBytes: 15 * 1024 * 1024
    }
    }
    });

    await server.register(require('@hapi/inert'));

    await server.start();
    console.log('Server running on %s', server.info.uri);
    };

    process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
    });

    init();