Skip to content

Instantly share code, notes, and snippets.

@m-esm
Created February 22, 2019 11:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m-esm/ad397af08f8d37baee94173559e26daf to your computer and use it in GitHub Desktop.
Save m-esm/ad397af08f8d37baee94173559e26daf to your computer and use it in GitHub Desktop.
Node.js sending and receiving file using only 'http' and 'fs' module (no framework)
var http = require("http");
var fs = require("fs");
var server = http.createServer().listen(3000);
server.on("request", function(req, res) {
if (req.method != "POST") return res.end();
var imageName = "received-" + Date.now() + ".jpg";
var writeStream = fs.createWriteStream(imageName);
req.pipe(writeStream);
req.on("end", function() {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("saved as:\n\t" + imageName);
});
});
console.log("Listening on port 3000");
var options = {
hostname: "localhost",
port: 3000,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": fs.statSync("send.jpg").size
}
};
var req = http.request(options, function(res) {
console.log("STATUS:", res.statusCode);
console.log("HEADERS:", JSON.stringify(res.headers));
res.setEncoding("utf8");
res.on("data", function(chunk) {
console.log("Response chunk:", chunk);
});
res.on("end", function() {
console.log("Request End");
});
});
req.on("error", function(e) {
console.log("Problem with request:", e.message);
});
var readStream = fs.createReadStream("send.jpg");
readStream.pipe(req);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment