0

I am writing a server that is meant to serve and receive files. It is written in node.js, using express.js. I also have a client, also written in node, which is meant to send a request to the server and receive the files on the server.

Server-side

const express = require("express");
const app = express();
const file = "./samplefiles/Helloworld.txt";

app.get("/", (res)=>{
    res.download(file);
});

module.exports = app; //this exports to server.js
const http = require("http");
const app = require("./app.js);
const port = 8080;

const server = http.createServer(app);

server.listen(port, () => {
    console.clear();
    console.log("server running");
})

Client-side

const request = require("request");

request.get("http://localhost:8080/", (req, body) => {
    console.log(body);
    console.log(res);
});

If I try to access it by my browser I am asked what I want to do with the file, it works. However, Is I run my client-side code it prints the body and the res(being null). I expected the file name and it's content to be in the body but only the content of the file was in the body.

I want to receive the whole file, is possible, or at least get the name of it so that I can "make" a copy of it on the client-side.

MoltasDev
  • 65
  • 1
  • 7

3 Answers3

0

Change code your server side to:

const port = 8080;
const express = require("express");
const app = express();
const path = require('path');
app.get("/", function(req, res){
    res.sendFile(path.join(__dirname, 'app.js'));
});

app.listen(port, () => {
console.clear();
console.log("server running");
});

Change code your client-side to:

var request = require('request');
request('http://localhost:8080/', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print data of your file
});

You need to install request npm i request for client side

0

You can serve up any files you want with express static method:

app.use(express.static('public'))

in this case just put all the files you want to serve in folder called public and then you can access it by localhost:8080/Helloworld.txt.

Cuong Nguyen
  • 314
  • 2
  • 8
0

I ended up working around it.

I sent the file name as a header and was thus able to create a replica of the file I wanted to download using the body info and the filenameheader.

MoltasDev
  • 65
  • 1
  • 7