Skip to content

Instantly share code, notes, and snippets.

@simone-sanfratello
Last active July 24, 2020 07:40
Show Gist options
  • Save simone-sanfratello/d6f51a9c0109acdeed05f9164a6862f3 to your computer and use it in GitHub Desktop.
Save simone-sanfratello/d6f51a9c0109acdeed05f9164a6862f3 to your computer and use it in GitHub Desktop.
node.js training
const http = require('http')
const baseUrl = 'httpbin.org'
http.createServer((request, response) => {
const forward = http.request({
host: baseUrl,
path: request.url,
method: request.method,
headers: request.headers
}, (fresponse) => {
fresponse.pipe(response)
})
request.pipe(forward)
}).listen(3000)
const http = require('http')
const fs = require('fs')
const url = require('url')
const path = require('path')
const mime = require('mime')
const got = require('got')
const assert = require('assert').strict
const root = __dirname
http.createServer((request, response) => {
const uri = url.parse(request.url).pathname
const file = path.join(root, uri)
fs.stat(file, (err, stat) => {
if (err || !stat.isFile()) {
response.writeHead(404, {
'Content-Type': 'text/plain'
})
response.write('NOT_FOUND')
response.end()
return
}
const stream = fs.createReadableStream(file)
stream.on('open', () => {
response.writeHead(200, {
'Content-Type': mime.getType(path.extname(file)) || 'application/octet',
'Content-Length': stat.size
})
stream.pipe(response)
})
stream.on('error', () => {
response.writeHead(500, {
'Content-Type': 'text/plain'
})
response.write('SERVER_ERROR')
response.end()
})
})
}).listen(8080)
async function test() {
const cases = [
{
url: 'http://localhost:8080/mime/img.png',
status: 200,
type: 'image/png'
},
{
url: 'http://localhost:8080/mime/cli.js',
status: 200,
type: 'application/javascript'
},
{
url: 'http://localhost:8080/naa',
status: 404,
type: 'text/plain'
}
]
for (const case_ of cases) {
const response = await got(case_.url, { throwHttpErrors: false })
assert.equal(case_.status, response.statusCode)
assert.equal(case_.type, response.headers['content-type'])
console.log(case_.url, 'ok')
}
}
test()
const fastify = require('fastify')
const he = require('he')
const got = require('got')
const assert = require('assert').strict
function server() {
const app = fastify()
app.get('/q', (request, response) => {
try {
if (request.query.message) {
response.send(request.query.message.toUpperCase())
return
}
} catch (error) {
response.code(400).send('ERROR')
}
})
return app
}
async function test () {
const app = server()
await app.listen(0)
app.server.unref()
const address = app.server.address()
const url = `http://${address.address}:${address.port}`
const response = await got(url + '/q?message=ciao', { throwHttpErrors: false })
assert.equal(response.body, 'CIAO')
assert.equal(response.headers['content-type'], 'text/plain; charset=utf-8')
assert.equal(response.statusCode, 200)
await app.close()
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment