Created
May 25, 2019 19:58
-
-
Save fselcukcan/13d44f8edc9cc74b05571f9d478a1c15 to your computer and use it in GitHub Desktop.
hapi file-upload and save to file
This file contains 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
'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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment