-
-
Save AliSawari/5c57e1f67e22fa6ea0bcd3f8fb3e1a70 to your computer and use it in GitHub Desktop.
Node.js sending and receiving file using only 'http' and 'fs' module (no framework)
This file contains hidden or 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
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