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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
-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);

1 Comment

Did OP not mention HTTPS?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.