Search code examples
node.jshttpsfileserver

Node.js quick file server (static files over HTTPS)


I've managed to create https server with node by using those commands from node.js application:

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

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);

What I would like to do is make https server run from folder, something similiar like this, which is for http-server. So if I later add file inside https folder, file can easily be reached from https://localhost:4433/main.js (main.js is just an example file). Is it possible to do it for https?


Solution

  • Yes, it is possible.

    Refer this answer npm http-server with SSL

    OR

    Step 1. Write a server

    You can use pure node.js modules to serve static files or you can use an express framework to solve your issue. https://expressjs.com/en/starter/static-files.html

    Step 2. Write a command-line script

    You have to write a script and preferably saves into the bin folder, that accepts the command-line arguments such as folder path, port, etc. and starts the server. Also, you can use node.js to write such scripts using commander.js, etc.