0

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?

FrenkyB
  • 6,625
  • 14
  • 67
  • 114

2 Answers2

0

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.

Roshan Gade
  • 320
  • 3
  • 16
  • 1
    The first link in you answer did it and it's quite simple: http-server -S -a localhost -p 442 -C certificate.pem -K privatekey.pem – FrenkyB Nov 20 '19 at 07:29
-1
  1. find URL in the request
  2. make URL become your folder file path
  3. read file data by file path
  4. response to the file data

example if your folder has 1.txt 2.html

  • localhost:8000/1.txt will get 1.txt
  • localhost:8000/2.html will get 2.html
const http = require('http')
const fs = require('fs')
const path = require('path');

const server = http.createServer((req, res) => {  
  var filePath = path.join('.',req.url)
  // Browser will autorequest 'localhost:8000/favicon.ico'
  if ( !(filePath == "favicon.ico") ) {
    file = fs.readFileSync(filePath,'utf-8')
    res.write(file)
  }
  res.end();
});

server.listen(8000);
Lei Cui
  • 62
  • 1
  • 3