Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CRUD over a folder over HTTP
const formidable = require('formidable')
const fs = require('fs-extra')
const path = require('path')
module.exports = ({path: _path}) => {
fs.ensureDirSync(_path)
return async (req, res) => {
const method = req.method.toLowerCase()
switch (method) {
case 'get':
await get(_path, req, res)
break
case 'post':
await post(_path, req, res)
break
case 'delete':
await del(_path, req, res)
break
}
jsonResponse(res, {url: req.url})
}
function jsonResponse (res, json) {
res.writeHead(200, {'content-type': 'application/json'})
res.end(JSON.stringify(json))
}
async function get(root, req, res) {
const fullPath = req.url.slice(1)
const folderName = path.resolve(root, path.dirname(fullPath))
}
async function post(root, req, res) {
const fullPath = req.url.slice(1)
const files = await getFile(req)
let folderName
if (files.length > 1) {
folderName = path.resolve(root, fullPath)
} else {
folderName = path.resolve(root, path.dirname(fullPath))
}
await fs.ensureDir(folderName)
if (files.length > 1) {
for (let file of files) {
await fs.move(file.path, path.resolve(folderName, file.name))
}
} else {
await fs.move(files[0].path, path.resolve(folderName, path.basename(fullPath)))
}
}
async function del(root, req, res) {
const fullPath = req.url.slice(1)
const folderName = path.resolve(root, path.dirname(fullPath))
}
function getFile (req) {
return new Promise((resolve, reject) => {
const form = new formidable.IncomingForm()
form.maxFieldsSize = 100 * 1024 * 1024
form.parse(req, (err, fields, files) => {
if (err) {
reject(err)
} else {
resolve(Object.keys(files).map(k => files[k]))
}
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.