Chapter 4: initial recipe samples

This commit is contained in:
Beth Griggs
2020-04-29 22:00:34 +01:00
parent 503edc4ec2
commit bcf782f7dc
59 changed files with 471 additions and 655 deletions
+13
View File
@@ -0,0 +1,13 @@
{
"name": "file-upload",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"formidable": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/formidable/-/formidable-1.2.2.tgz",
"integrity": "sha512-V8gLm+41I/8kguQ4/o1D3RIHRmhYFG4pnNyonvua+40rqcEmT4+V71yaZ3B457xbbgCsCfjSPi65u/W6vK1U5Q=="
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "file-upload",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"formidable": "^1.2.2"
}
}
+5
View File
@@ -0,0 +1,5 @@
<form method="POST" enctype="multipart/form-data">
<label for="userfile">File:</label>
<input type="file" id="userfile" name="userfile"><br>
<input type="submit">
</form>
+55
View File
@@ -0,0 +1,55 @@
const fs = require('fs')
const http = require('http')
const path = require('path')
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
const formidable = require('formidable')
http.createServer((req, res) => {
if (req.method === 'GET') {
get(res)
return
}
if (req.method === 'POST') {
post(req, res)
return
}
error(405, res)
}).listen(3000)
function get(res) {
res.writeHead(200, {
'Content-Type': 'text/html'
})
res.end(form)
}
function post(req, res) {
if (!/multipart\/form-data/.test(req.headers['content-type'])) {
error(415, res)
return
}
const form = formidable({
multiples: true,
uploadDir: './uploads'
});
form.parse(req, (err, fields, files) => {
if (err) return err
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
fields,
files
}))
})
}
function error(code, res) {
res.statusCode = code
res.end(http.STATUS_CODES[code])
}