Skip to content

Instantly share code, notes, and snippets.



Forked from m-esm/run.js
Created Feb 22, 2019
What would you like to do?
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-" + + ".jpg";
var writeStream = fs.createWriteStream(imageName);
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.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");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.