1

I'm very new to Node JS and would appreciate any help/advice.

Using NodeJS, I have created a local server run this link (it's simply a hello world)

From there, I have used this stack overflow snippet , which responds by the request type made.

I'd like to take this a step further, and when the reponse.method is get/post/etc. - I'd like the response to be a file.

In other words, I'd like to return a file from a HTTP response.

In theory, something along the lines of:

if(request.method == "GET")
{
    response.end("C:\[file path]\test.txt");
}

I've tried simply copying/pasting the file directory after response.end('file directory') but was not opening the file that I wanted it to.

const http = require("http");
const hostname = '127.0.0.1';
const port = 8091;

var server = http.createServer ( function(request,response){

response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
    {
        response.end("received GET request.")
    }
else if(request.method == "POST")
    {
        response.end("received POST request.");
    }
else
    {
        response.end("Undefined request .");
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Jett
  • 781
  • 1
  • 14
  • 30

1 Answers1

1

You can send file data by first reading the file using the fs module's readFile method, and then sending it via res.write() followed by res.end(), or just res.end() as you have done. Here's an example:

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function(req, res) {
    if (req.method === 'GET' && req.url === '/') {
        fs.readFile('./index.html', function(err, data) {
            if (err){
                throw err;
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(data);
            return;
        });
    }
}).listen(3000);

I answered a similar question to this here: https://stackoverflow.com/a/56285824/4882724

David
  • 134
  • 1
  • 10