Code files
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "websocket-app",
|
||||
"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": {
|
||||
"ws": "^1.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<input id="msg"><button id="send">Send</button>
|
||||
<div id="output"></div>
|
||||
<script>
|
||||
(function () {
|
||||
var ws = new WebSocket('ws://localhost:8080')
|
||||
var output = document.getElementById('output')
|
||||
var send = document.getElementById('send')
|
||||
|
||||
function log (event, msg) {
|
||||
return '<div>' + event + ': ' + msg + '</div>';
|
||||
}
|
||||
|
||||
send.addEventListener('click', function () {
|
||||
var msg = document.getElementById('msg').value
|
||||
ws.send(msg)
|
||||
output.innerHTML += log('Sent', msg)
|
||||
})
|
||||
|
||||
ws.onmessage = function (e) {
|
||||
output.innerHTML += log('Received', e.data)
|
||||
}
|
||||
|
||||
ws.onclose = function (e) {
|
||||
output.innerHTML += log('Disconnected', e.code + '-' + e.type)
|
||||
}
|
||||
|
||||
ws.onerror = function (e) {
|
||||
output.innerHTML += log('Error', e.data);
|
||||
}
|
||||
}())
|
||||
</script>
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const ws = require('ws')
|
||||
|
||||
const app = fs.readFileSync('public/index.html')
|
||||
const server = http.createServer((req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.end(app)
|
||||
})
|
||||
const wss = new ws.Server({server})
|
||||
|
||||
wss.on('connection', (socket) => {
|
||||
socket.on('message', (msg) => {
|
||||
console.log(`Received: ${msg}`)
|
||||
console.log(`From IP: ${socket.upgradeReq.connection.remoteAddress}`)
|
||||
if (msg === 'Hello') socket.send('Websockets!')
|
||||
})
|
||||
})
|
||||
|
||||
server.listen(8080)
|
||||
@@ -0,0 +1,39 @@
|
||||
'use strict'
|
||||
|
||||
const WebSocket = require('ws')
|
||||
const readline = require('readline')
|
||||
const ws = new WebSocket(process.argv[2] || 'ws://localhost:8080')
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
prompt: '-> '
|
||||
})
|
||||
const gray = '\u001b[90m'
|
||||
const red = '\u001b[31m'
|
||||
const reset = '\u001b[39m'
|
||||
ws.on('open', () => {
|
||||
rl.output.write(`${gray}-- Connected --${reset}\n\n`)
|
||||
rl.prompt()
|
||||
})
|
||||
rl.on('line', (msg) => {
|
||||
ws.send(msg, () => {
|
||||
rl.output.write(`${gray}<= ${msg}${reset}\n\n`)
|
||||
rl.prompt()
|
||||
})
|
||||
})
|
||||
ws.on('message', function (msg) {
|
||||
readline.clearLine(rl.output)
|
||||
readline.moveCursor(rl.output, -3 - rl.line.length, -1)
|
||||
rl.output.write(`${gray}=> ${msg}${reset}\n\n`)
|
||||
rl.prompt(true)
|
||||
})
|
||||
ws.on('close', () => {
|
||||
readline.cursorTo(rl.output, 0)
|
||||
rl.output.write(`${gray}-- Disconnected --${reset}\n\n`)
|
||||
process.exit()
|
||||
})
|
||||
ws.on('error', (err) => {
|
||||
readline.cursorTo(rl.output, 0)
|
||||
rl.output.write(`${red}-- Error --${reset}\n`)
|
||||
rl.output.write(`${red}${err.stack}${reset}\n`)
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "websocket-client",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"ws": "^1.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const qs = require('querystring')
|
||||
const url = require('url')
|
||||
|
||||
const host = process.env.HOST || '0.0.0.0'
|
||||
const port = process.env.PORT || 8080
|
||||
|
||||
const userList = [
|
||||
{'id': 1, 'first_name': 'Bob', 'second_name': 'Smith', type: 'red'},
|
||||
{'id': 2, 'first_name': 'David', 'second_name': 'Clements', type: 'blue'}
|
||||
]
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method !== 'GET') return error(res, 405)
|
||||
if (req.url === '/') return index(res)
|
||||
const {pathname, query} = url.parse(req.url)
|
||||
if (pathname === '/users') return users(query, res)
|
||||
|
||||
error(res, 404)
|
||||
})
|
||||
|
||||
function error (res, code) {
|
||||
res.statusCode = code
|
||||
res.end(`{"error": "${http.STATUS_CODES[code]}"}`)
|
||||
}
|
||||
|
||||
function users (query, res) {
|
||||
const {type} = qs.parse(query)
|
||||
const list = !type ? userList : userList.filter((user) => user.type === type)
|
||||
res.end(`{"data": ${JSON.stringify(list)}}`)
|
||||
}
|
||||
|
||||
function index (res) {
|
||||
res.end('{"name": "my-rest-server", "version": 0}')
|
||||
}
|
||||
|
||||
server.listen(port, host)
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const url = require('url')
|
||||
|
||||
const host = process.env.HOST || '0.0.0.0'
|
||||
const port = process.env.PORT || 8080
|
||||
|
||||
const userList = [
|
||||
{'id': 1, 'first_name': 'Bob', 'second_name': 'Smith', type: 'red'},
|
||||
{'id': 2, 'first_name': 'David', 'second_name': 'Clements', type: 'blue'}
|
||||
]
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method !== 'GET') return error(res, 405)
|
||||
if (req.url === '/') return index(res)
|
||||
const {pathname, query} = url.parse(req.url, true)
|
||||
if (pathname === '/users') return users(query, res)
|
||||
|
||||
error(res, 404)
|
||||
})
|
||||
|
||||
function error (res, code) {
|
||||
res.statusCode = code
|
||||
res.end(`{"error": "${http.STATUS_CODES[code]}"}`)
|
||||
}
|
||||
|
||||
function users ({type}, res) {
|
||||
const list = !type ? userList : userList.filter((user) => user.type === type)
|
||||
res.end(`{"data": ${JSON.stringify(list)}}`)
|
||||
}
|
||||
|
||||
function index (res) {
|
||||
res.end('{"name": "my-rest-server", "version": 0}')
|
||||
}
|
||||
|
||||
server.listen(port, host)
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
|
||||
const host = process.env.HOST || '0.0.0.0'
|
||||
const port = process.env.PORT || 0
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method !== 'GET') return error(res, 405)
|
||||
if (req.url === '/users') return users(res)
|
||||
if (req.url === '/') return index(res)
|
||||
error(res, 404)
|
||||
})
|
||||
|
||||
function error (res, code) {
|
||||
res.statusCode = code
|
||||
res.end(`{"error": "${http.STATUS_CODES[code]}"}`)
|
||||
}
|
||||
|
||||
function users (res) {
|
||||
res.end('{"data": [{"id": 1, "first_name": "Bob", "second_name": "Smith"}]}')
|
||||
}
|
||||
|
||||
function index (res) {
|
||||
res.end('{"name": "my-rest-server", "version": 0}')
|
||||
}
|
||||
|
||||
server.listen(port, host, () => console.log(JSON.stringify(server.address())))
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
|
||||
const host = process.env.HOST || '0.0.0.0'
|
||||
const port = process.env.PORT || 8080
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method !== 'GET') return error(res, 405)
|
||||
if (req.url === '/users') return users(res)
|
||||
if (req.url === '/') return index(res)
|
||||
error(res, 404)
|
||||
})
|
||||
|
||||
function error (res, code) {
|
||||
res.statusCode = code
|
||||
res.end(`{"error": "${http.STATUS_CODES[code]}"}`)
|
||||
}
|
||||
|
||||
function users (res) {
|
||||
res.end('{"data": [{"id": 1, "first_name": "Bob", "second_name": "Smith"}]}')
|
||||
}
|
||||
|
||||
function index (res) {
|
||||
res.end('{"name": "my-rest-server", "version": 0}')
|
||||
}
|
||||
|
||||
server.listen(port, host)
|
||||
@@ -0,0 +1,61 @@
|
||||
'use strict'
|
||||
|
||||
const os = require('os')
|
||||
const readline = require('readline')
|
||||
const smtp = require('smtp-protocol')
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
prompt: ''
|
||||
})
|
||||
|
||||
const cfg = {
|
||||
host: 'localhost',
|
||||
port: 2525,
|
||||
email: 'me@me.com',
|
||||
hostname: os.hostname()
|
||||
}
|
||||
|
||||
rl.on('SIGINT', () => {
|
||||
console.log('... cancelled ...')
|
||||
process.exit()
|
||||
})
|
||||
|
||||
smtp.connect(cfg.host, cfg.port, (mail) => {
|
||||
mail.helo(cfg.hostname)
|
||||
mail.from(cfg.email)
|
||||
rl.question('To: ', (to) => {
|
||||
to.split(/;|,/gm).forEach((rcpt) => {
|
||||
rcpt = rcpt.trim()
|
||||
mail.to(rcpt, (err, code, lines) => {
|
||||
exitOnFail(err, code, lines, {rcpt: rcpt})
|
||||
})
|
||||
})
|
||||
rl.write('===== Message (^D to send) =====\n')
|
||||
mail.data(exitOnFail)
|
||||
const body = []
|
||||
rl.on('line', (line) => body.push(`${line}\r\n`))
|
||||
rl.on('close', () => send(mail, body))
|
||||
})
|
||||
})
|
||||
|
||||
function send (mail, body) {
|
||||
console.log('... sending ...')
|
||||
const message = mail.message()
|
||||
body.forEach(message.write, message)
|
||||
message.end()
|
||||
mail.quit()
|
||||
}
|
||||
|
||||
function exitOnFail (err, code, lines, info) {
|
||||
if (code === 550) {
|
||||
err = Error(`No Mailbox for Recipient "${info.rcpt}"`)
|
||||
}
|
||||
if (!err && code !== 354 && code !== 250 && code !== 220 && code !== 200) {
|
||||
err = Error(`Protocol Error: ${code} ${lines.join('')}`)
|
||||
}
|
||||
if (!err) return
|
||||
console.error(err.message)
|
||||
process.exit(1)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "smtp-client",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"smtp-protocol": "^2.4.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
'use strict'
|
||||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const smtp = require('smtp-protocol')
|
||||
const hosts = new Set(['localhost', 'example.com'])
|
||||
const users = new Set(['you', 'another'])
|
||||
const mailDir = path.join(__dirname, 'mail')
|
||||
|
||||
function ensureDir (dir, cb) {
|
||||
try { fs.mkdirSync(dir) } catch (e) {
|
||||
if (e.code !== 'EEXIST') throw e
|
||||
}
|
||||
}
|
||||
|
||||
ensureDir(mailDir)
|
||||
for (let user of users) ensureDir(path.join(mailDir, user))
|
||||
|
||||
const server = smtp.createServer((req) => {
|
||||
req.on('to', filter)
|
||||
req.on('message', (stream, ack) => save(req, stream, ack))
|
||||
req.on('error', (err) => console.error(err))
|
||||
})
|
||||
|
||||
server.listen(2525)
|
||||
|
||||
function filter (to, {accept, reject}) {
|
||||
const [user, host] = to.split('@')
|
||||
if (hosts.has(host) && users.has(user)) {
|
||||
accept()
|
||||
return
|
||||
}
|
||||
reject(550, 'mailbox not available')
|
||||
}
|
||||
|
||||
function save (req, stream, {accept}) {
|
||||
const {from, to} = req
|
||||
accept()
|
||||
to.forEach((rcpt) => {
|
||||
const [user] = rcpt.split('@')
|
||||
const dest = path.join(mailDir, user, `${from}-${Date.now()}`)
|
||||
const mail = fs.createWriteStream(dest)
|
||||
mail.write(`From: ${from} \n`)
|
||||
mail.write(`To: ${rcpt} \n\n`)
|
||||
stream.pipe(mail, {end: false})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "smtp",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "David Mark Clements",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"smtp-protocol": "^2.4.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "uploading-a-file",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "David Mark Clements",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"multipart-read-stream": "^1.0.1",
|
||||
"pump": "^1.0.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="text" name="userinput1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
@@ -0,0 +1,65 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const mrs = require('multipart-read-stream')
|
||||
const pump = require('pump')
|
||||
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
|
||||
|
||||
http.createServer((req, res) => {
|
||||
if (req.method === 'GET') {
|
||||
get(res)
|
||||
return
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
post(req, res)
|
||||
return
|
||||
}
|
||||
reject(405, 'Method Not Allowed', res)
|
||||
}).listen(8080)
|
||||
|
||||
function get (res) {
|
||||
res.writeHead(200, {'Content-Type': 'text/html'})
|
||||
res.end(form)
|
||||
}
|
||||
|
||||
function reject (code, msg, res) {
|
||||
res.statusCode = code
|
||||
res.end(msg)
|
||||
}
|
||||
|
||||
function post (req, res) {
|
||||
if (!/multipart\/form-data/.test(req.headers['content-type'])) {
|
||||
reject(415, 'Unsupported Media Type', res)
|
||||
return
|
||||
}
|
||||
console.log('parsing multipart data')
|
||||
const parser = mrs(req, res, part, () => {
|
||||
console.log('finished parsing')
|
||||
})
|
||||
parser.on('field', (field, value) => {
|
||||
console.log(`${field}: ${value}`)
|
||||
res.write(`processed "${field}" input.\n`)
|
||||
})
|
||||
var total = 0
|
||||
pump(req, parser)
|
||||
|
||||
function part (field, file, name) {
|
||||
if (!name) {
|
||||
file.resume()
|
||||
return
|
||||
}
|
||||
total += 1
|
||||
const filename = `${field}-${Date.now()}-${name}`
|
||||
const dest = fs.createWriteStream(path.join(__dirname, 'uploads', filename))
|
||||
pump(file, dest, (err) => {
|
||||
total -= 1
|
||||
res.write(err
|
||||
? `Error saving ${name}!\n`
|
||||
: `${name} successfully saved!\n`
|
||||
)
|
||||
if (total === 0) res.end('All files processed!')
|
||||
})
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "uploading-a-file-with-put",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "David Mark Clements",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pump": "^1.0.1",
|
||||
"through2": "^2.0.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<form id="upload">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
<pre id="status"></pre>
|
||||
<script>
|
||||
(function () {
|
||||
var fieldName = 'userfile1'
|
||||
var field = document.querySelector('[name=' + fieldName + ']')
|
||||
var uploadForm = document.getElementById('upload')
|
||||
var status = document.getElementById('status')
|
||||
var file
|
||||
field.addEventListener('change', function () {
|
||||
file = this.files[0]
|
||||
})
|
||||
uploadForm.addEventListener('submit', function (e) {
|
||||
e.preventDefault()
|
||||
if (!file) return
|
||||
var xhr = new XMLHttpRequest()
|
||||
xhr.file = file
|
||||
xhr.open('put', window.location, true)
|
||||
xhr.setRequestHeader("x-field", fieldName)
|
||||
xhr.setRequestHeader("x-filename", file.fileName || file.name)
|
||||
xhr.onload = updateStatus
|
||||
xhr.send(file)
|
||||
file = ''
|
||||
uploadForm.reset()
|
||||
})
|
||||
function updateStatus() {
|
||||
status.innerHTML += this.status === 200
|
||||
? this.response
|
||||
: this.status + ': ' + this.response
|
||||
}
|
||||
}())
|
||||
</script>
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const pump = require('pump')
|
||||
const through = require('through2')
|
||||
const form = fs.readFileSync('public/form.html')
|
||||
const maxFileSize = 51200
|
||||
|
||||
http.createServer((req, res) => {
|
||||
if (req.method === 'GET') {
|
||||
get(res)
|
||||
return
|
||||
}
|
||||
if (req.method === 'PUT') {
|
||||
put(req, res)
|
||||
return
|
||||
}
|
||||
reject(405, 'Method Not Allowed', res)
|
||||
}).listen(8080)
|
||||
|
||||
function get (res) {
|
||||
res.writeHead(200, {'Content-Type': 'text/html'})
|
||||
res.end(form)
|
||||
}
|
||||
|
||||
function reject (code, msg, res) {
|
||||
res.statusCode = code
|
||||
res.end(msg)
|
||||
}
|
||||
|
||||
function put (req, res) {
|
||||
const size = parseInt(req.headers['content-length'], 10)
|
||||
if (isNaN(size)) {
|
||||
reject(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
if (size > maxFileSize) {
|
||||
reject(413, 'Too Large', res)
|
||||
return
|
||||
}
|
||||
|
||||
const name = req.headers['x-filename']
|
||||
const field = req.headers['x-field']
|
||||
const filename = `${field}-${Date.now()}-${name}`
|
||||
const dest = fs.createWriteStream(path.join(__dirname, 'uploads', filename))
|
||||
const counter = through(function (chunk, enc, cb) {
|
||||
this.bytes += chunk.length
|
||||
if (this.bytes > maxFileSize) {
|
||||
cb(Error('size'))
|
||||
return
|
||||
}
|
||||
cb(null, chunk)
|
||||
})
|
||||
counter.bytes = 0
|
||||
counter.on('error', (err) => {
|
||||
if (err.message === 'size') reject(413, 'Too Large', res)
|
||||
})
|
||||
pump(req, counter, dest, (err) => {
|
||||
if (err) return reject(500, `Error saving ${name}!\n`, res)
|
||||
res.end(`${name} successfully saved!\n`)
|
||||
})
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "uploading-a-file",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "David Mark Clements",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"multipart-read-stream": "^3.0.0",
|
||||
"pump": "^1.0.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<form method="POST" enctype="multipart/form-data">
|
||||
<input type="file" name="userfile1"><br>
|
||||
<input type="file" name="userfile2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
@@ -0,0 +1,59 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const mrs = require('multipart-read-stream')
|
||||
const pump = require('pump')
|
||||
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
|
||||
|
||||
http.createServer((req, res) => {
|
||||
if (req.method === 'GET') {
|
||||
get(res)
|
||||
return
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
post(req, res)
|
||||
return
|
||||
}
|
||||
reject(405, 'Method Not Allowed', res)
|
||||
}).listen(8080)
|
||||
|
||||
function get (res) {
|
||||
res.writeHead(200, {'Content-Type': 'text/html'})
|
||||
res.end(form)
|
||||
}
|
||||
|
||||
function reject (code, msg, res) {
|
||||
res.statusCode = code
|
||||
res.end(msg)
|
||||
}
|
||||
|
||||
function post (req, res) {
|
||||
if (!/multipart\/form-data/.test(req.headers['content-type'])) {
|
||||
reject(415, 'Unsupported Media Type', res)
|
||||
return
|
||||
}
|
||||
console.log('parsing multipart data')
|
||||
const parser = mrs(req.headers, part)
|
||||
var total = 0
|
||||
pump(req, parser)
|
||||
|
||||
function part (field, file, name) {
|
||||
if (!name) {
|
||||
file.resume()
|
||||
return
|
||||
}
|
||||
total += 1
|
||||
const filename = `${field}-${Date.now()}-${name}`
|
||||
const dest = fs.createWriteStream(path.join(__dirname, 'uploads', filename))
|
||||
pump(file, dest, (err) => {
|
||||
total -= 1
|
||||
res.write(err
|
||||
? `Error saving ${name}!\n`
|
||||
: `${name} successfully saved!\n`
|
||||
)
|
||||
if (total === 0) res.end('All files processed!')
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const assert = require('assert')
|
||||
const url = 'http://www.davidmarkclements.com/ncb3/some.json'
|
||||
|
||||
http.get(url, (res) => {
|
||||
const size = parseInt(res.headers['content-length'], 10)
|
||||
const buffer = Buffer.allocUnsafe(size)
|
||||
var index = 0
|
||||
res.on('data', (chunk) => {
|
||||
chunk.copy(buffer, index)
|
||||
index += chunk.length
|
||||
})
|
||||
res.on('end', () => {
|
||||
assert.equal(size, buffer.length)
|
||||
console.log('GUID:', JSON.parse(buffer).guid)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const steed = require('steed')()
|
||||
const files = process.argv.slice(2)
|
||||
const boundary = Date.now()
|
||||
const opts = {
|
||||
method: 'POST',
|
||||
hostname: 'localhost',
|
||||
port: 8080,
|
||||
path: '/',
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data; boundary="' + boundary + '"',
|
||||
'Transfer-Encoding': 'chunked'
|
||||
}
|
||||
}
|
||||
|
||||
const req = http.request(opts, (res) => {
|
||||
console.log('\n Status: ' + res.statusCode)
|
||||
process.stdout.write(' Body: ')
|
||||
res.pipe(process.stdout)
|
||||
res.on('end', () => console.log('\n'))
|
||||
})
|
||||
|
||||
req.on('error', (err) => console.error('Error: ', err))
|
||||
|
||||
const parts = files.map((file, i) => (cb) => {
|
||||
const stream = fs.createReadStream(file)
|
||||
stream.once('open', () => {
|
||||
req.write(
|
||||
`\r\n--${boundary}\r\n` +
|
||||
'Content-Disposition: ' +
|
||||
`form-data; name="userfile${i}";` +
|
||||
`filename="${path.basename(file)}"\r\n` +
|
||||
'Content-Type: application/octet-stream\r\n' +
|
||||
'Content-Transfer-Encoding: binary\r\n' +
|
||||
'\r\n'
|
||||
)
|
||||
})
|
||||
stream.pipe(req, {end: false})
|
||||
stream.on('data', (chunk) => req.write(chunk))
|
||||
stream.on('end', cb)
|
||||
})
|
||||
|
||||
steed.series(parts, () => req.end(`\r\n--${boundary}--\r\n`))
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "multipart-post-uploads",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"steed": "^1.1.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const payload = `{
|
||||
"name": "Cian Ó Maidín",
|
||||
"company": "nearForm"
|
||||
}`
|
||||
const opts = {
|
||||
method: 'POST',
|
||||
hostname: 'reqres.in',
|
||||
port: 80,
|
||||
path: '/api/users',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload)
|
||||
}
|
||||
}
|
||||
|
||||
const req = http.request(opts, (res) => {
|
||||
console.log('\n Status: ' + res.statusCode)
|
||||
process.stdout.write(' Body: ')
|
||||
res.pipe(process.stdout)
|
||||
res.on('end', () => console.log('\n'))
|
||||
})
|
||||
|
||||
req.on('error', (err) => console.error('Error: ', err))
|
||||
|
||||
req.end(payload)
|
||||
@@ -0,0 +1,26 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const opts = {
|
||||
method: 'POST',
|
||||
hostname: 'reqres.in',
|
||||
port: 80,
|
||||
path: '/api/users',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Transfer-Encoding': 'chunked'
|
||||
}
|
||||
}
|
||||
|
||||
const req = http.request(opts, (res) => {
|
||||
console.log('\n Status: ' + res.statusCode)
|
||||
process.stdout.write(' Body: ')
|
||||
res.pipe(process.stdout)
|
||||
res.on('end', () => console.log('\n'))
|
||||
})
|
||||
|
||||
req.on('error', (err) => console.error('Error: ', err))
|
||||
|
||||
http.get('http://reqres.in/api/users', (res) => {
|
||||
res.pipe(req)
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "accepting-json",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "David Mark Clements",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-json-parse": "^1.0.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<form method="post">
|
||||
<input type="text" name="userinput1"><br>
|
||||
<input type="text" name="userinput2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
<script>
|
||||
document.forms[0].addEventListener('submit', function (evt) {
|
||||
evt.preventDefault()
|
||||
var form = this
|
||||
var data = Object.keys(form).reduce(function (o, i) {
|
||||
if (form[i].name) o[form[i].name] = form[i].value
|
||||
return o
|
||||
}, {})
|
||||
form.innerHTML = ''
|
||||
var xhr = new XMLHttpRequest()
|
||||
xhr.open('POST', '/')
|
||||
xhr.setRequestHeader('Content-Type', 'application/json')
|
||||
xhr.send(JSON.stringify(data))
|
||||
xhr.addEventListener('load', function () {
|
||||
var res
|
||||
try { res = JSON.parse(this.response) } catch (e) {
|
||||
res = {error: 'Mangled Response'}
|
||||
}
|
||||
form.innerHTML = res.error
|
||||
? res.error
|
||||
: 'You Posted: ' + JSON.stringify(res.data)
|
||||
})
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,73 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const parse = require('fast-json-parse')
|
||||
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
|
||||
const maxData = 2 * 1024 * 1024 // 2mb
|
||||
|
||||
http.createServer((req, res) => {
|
||||
if (req.method === 'GET') {
|
||||
get(res)
|
||||
return
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
post(req, res)
|
||||
return
|
||||
}
|
||||
reject(405, 'Method Not Allowed', res)
|
||||
}).listen(8080)
|
||||
|
||||
function get (res) {
|
||||
res.writeHead(200, {'Content-Type': 'text/html'})
|
||||
res.end(form)
|
||||
}
|
||||
|
||||
function post (req, res) {
|
||||
if (req.headers['content-type'] !== 'application/json') {
|
||||
reject(415, 'Unsupported Media Type', res)
|
||||
return
|
||||
}
|
||||
const size = parseInt(req.headers['content-length'], 10)
|
||||
if (isNaN(size)) {
|
||||
reject(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
if (size > maxData) {
|
||||
reject(413, 'Too Large', res)
|
||||
return
|
||||
}
|
||||
const buffer = Buffer.allocUnsafe(size)
|
||||
var pos = 0
|
||||
|
||||
req
|
||||
.on('data', (chunk) => {
|
||||
const offset = pos + chunk.length
|
||||
if (offset > size) {
|
||||
reject(413, 'Too Large', res)
|
||||
return
|
||||
}
|
||||
chunk.copy(buffer, pos)
|
||||
pos = offset
|
||||
})
|
||||
.on('end', () => {
|
||||
if (pos !== size) {
|
||||
reject(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
const data = buffer.toString()
|
||||
const parsed = parse(data)
|
||||
if (parsed.err) {
|
||||
reject(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
console.log('User Posted: ', parsed.value)
|
||||
res.end('{"data": ' + data + "}")
|
||||
})
|
||||
}
|
||||
|
||||
function reject (code, msg, res) {
|
||||
res.statusCode = code
|
||||
res.end(msg)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<form method="post">
|
||||
<input type="text" name="userinput1"><br>
|
||||
<input type="text" name="userinput2"><br>
|
||||
<input type="submit">
|
||||
</form>
|
||||
@@ -0,0 +1,68 @@
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const form = fs.readFileSync(path.join(__dirname, 'public', 'form.html'))
|
||||
const qs = require('querystring')
|
||||
const maxData = 2 * 1024 * 1024 // 2mb
|
||||
|
||||
http.createServer((req, res) => {
|
||||
if (req.method === 'GET') {
|
||||
get(res)
|
||||
return
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
post(req, res)
|
||||
return
|
||||
}
|
||||
reject(405, 'Method Not Allowed', res)
|
||||
}).listen(8080)
|
||||
|
||||
function get (res) {
|
||||
res.writeHead(200, {'Content-Type': 'text/html'})
|
||||
res.end(form)
|
||||
}
|
||||
|
||||
function post (req, res) {
|
||||
if (req.headers['content-type'] !== 'application/x-www-form-urlencoded') {
|
||||
reject(415, 'Unsupported Media Type', res)
|
||||
return
|
||||
}
|
||||
const size = parseInt(req.headers['content-length'], 10)
|
||||
if (isNaN(size)) {
|
||||
reject(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
if (size > maxData) {
|
||||
reject(413, 'Too Large', res)
|
||||
return
|
||||
}
|
||||
const buffer = Buffer.allocUnsafe(size)
|
||||
var pos = 0
|
||||
|
||||
req
|
||||
.on('data', (chunk) => {
|
||||
const offset = pos + chunk.length
|
||||
if (offset > size) {
|
||||
reject(413, 'Too Large', res)
|
||||
return
|
||||
}
|
||||
chunk.copy(buffer, pos)
|
||||
pos = offset
|
||||
})
|
||||
.on('end', () => {
|
||||
if (pos !== size) {
|
||||
reject(400, 'Bad Request', res)
|
||||
return
|
||||
}
|
||||
const data = qs.parse(buffer.toString())
|
||||
console.log('User Posted: ', data)
|
||||
res.end('You Posted: ' + JSON.stringify(data))
|
||||
})
|
||||
}
|
||||
|
||||
function reject (code, msg, res) {
|
||||
res.statusCode = code
|
||||
res.end(msg)
|
||||
}
|
||||
Reference in New Issue
Block a user