Created
December 14, 2022 17:03
-
-
Save yawboakye/71b6b7f3176e13d2001441552aa61e47 to your computer and use it in GitHub Desktop.
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
const assert = require("node:assert") | |
const http = require("node:http"); | |
const fs = require("node:fs"); | |
const imagePath = "./gh-woman_200x250.jpeg"; | |
function bytesPayload() { | |
const image = fs.readFileSync(imagePath); | |
const options = { | |
host: "localhost", | |
port: "5566", | |
path: "/binary", | |
method: "POST", | |
headers: { | |
"content-type": "application/octet-stream", | |
"content-length": Buffer.byteLength(image), | |
}, | |
}; | |
return [image, options]; | |
} | |
function base64Payload() { | |
const base64 = fs.readFileSync(imagePath).toString("base64"); | |
const options = { | |
host: "localhost", | |
port: "5566", | |
path: "/base64", | |
method: "POST", | |
headers: { | |
"content-type": "text/plain", | |
"content-length": Buffer.byteLength(base64), | |
}, | |
}; | |
return [base64, options]; | |
} | |
function bufferJsonPayload() { | |
const bufferJSON = fs.readFileSync(imagePath).toJSON(); | |
const asBody = JSON.stringify(bufferJSON); | |
const options = { | |
host: "localhost", | |
port: "5566", | |
path: "/buffer", | |
method: "POST", | |
headers: { | |
"content-type": "application/json", | |
"content-length": Buffer.byteLength(asBody), | |
}, | |
}; | |
return [asBody, options]; | |
} | |
function prepareRequest(payloadFormat) { | |
switch (payloadFormat) { | |
case "binary": return bytesPayload(); | |
case "base64": return base64Payload(); | |
case "buffer": return bufferJsonPayload(); | |
} | |
} | |
function makeRequest(payloadFormat) { | |
const [body, options] = prepareRequest(payloadFormat); | |
const req = http.request(options, (resp) => { | |
const chunks = [] | |
resp.on("data", chunk => chunks.push(chunk)); | |
resp.on("end", () => { | |
const destinationPath = Buffer.concat(chunks).toString(); | |
const sentImageStat = fs.statSync(imagePath) | |
const recvImageStat = fs.statSync(destinationPath) | |
assert( | |
sentImageStat.size === recvImageStat.size, | |
"Size mismatch between original and received: " + | |
`Sent: ${sentImageStat.size}; Recvd: ${recvImageStat.size}` | |
) | |
}); | |
}); | |
req.on("error", console.error); | |
req.write(body); | |
req.end(); | |
} | |
makeRequest("binary"); | |
makeRequest("base64"); | |
makeRequest("buffer"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment