Cannot transfer a file in Node.js using http module

96 views Asked by At

I am trying to send and receive a file in a typical client/server interaction:

  1. Client sends over a zip file.
  2. Server receives and saves it.

Client

const options = {
    hostname: "localhost",
    port: 8080,
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": fs.statSync("C:/users/Public/file.zip").size
    }
};

const clientRequest = http.request(options, res => {
    res.setEncoding('utf8');

    let data = "";
    res.on("data", (chunk) => {
        data += chunk;
    });

    res.on("end", () => {
        console.log(data);
    });
});

const zipFileStream = fs.createReadStream("C:/users/Public/file.zip");

zipFileStream.on("data", data => {
    clientRequest.write(data, "utf-8");
});

zipFileStream.on("end", () => {
    clientRequest.end(() => {
        console.log("Transmitted!");
    });
});

Server

http.createServer((req, res) => {
    req.on("data", (data) => {
        console.log(`Data received: ${data}`);

        const dstDir = "C:/users/Public";
        const dstPath = path.join(dstDir, `zip-${Math.ceil(Math.random()*100000)}.zip`);
        const dstStream = fs.createWriteStream(dstPath);
        dstStream.write(data, "utf-8", (error) => {
            if (error) {
                console.log(`Error while trying to save zip into ${dstPath}: ${error}`);
                return;
            }

            utils.log(`Data written into ${dstPath}`);
        });
    });
}).listen(8080);

The problem

The issue is that everything works fine and the server correctly receives the data and also saves the stream into the specified file. So in the end I get a zip file in the filesystem. When I try to open it:

Windows cannot open the folder. The Compressed (zip) folder "..." is invalid.

Seems like a serialization issue. But I specified the encoding so I thought I had it covered.

0

There are 0 answers