Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js快速文件服务器(HTTPS上的静态文件)_Node.js_Https_Fileserver - Fatal编程技术网

Node.js快速文件服务器(HTTPS上的静态文件)

Node.js快速文件服务器(HTTPS上的静态文件),node.js,https,fileserver,Node.js,Https,Fileserver,通过使用node.js应用程序中的以下命令,我成功地创建了带有node的https服务器: 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.pe

通过使用node.js应用程序中的以下命令,我成功地创建了带有node的https服务器:

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);
我想做的是让https服务器从文件夹中运行,类似于http服务器。所以,如果我以后在https文件夹中添加文件,可以从
https://localhost:4433/main.js
(main.js只是一个示例文件)。可以用https吗?

是的,可以

请参考此答案

步骤1。编写服务器

您可以使用纯node.js模块来提供静态文件,也可以使用express框架来解决您的问题

第2步。编写命令行脚本

您必须编写一个脚本,最好保存到bin文件夹中,该文件夹接受命令行参数,如文件夹路径、端口等,并启动服务器。此外,您还可以使用node.js来编写这样的脚本,例如

  • 在请求中查找URL
  • 使URL成为您的文件夹文件路径
  • 按文件路径读取文件数据
  • 对文件数据的响应
  • 示例:如果文件夹中有1.txt 2.html

    • localhost:8000/1.txt
      将获得1.txt
    • localhost:8000/2.html
      将获得2.html
    consthttp=require('http'))
    常量fs=require('fs')
    const path=require('path');
    const server=http.createServer((req,res)=>{
    var filePath=path.join('.',req.url)
    //浏览器将自动请求“localhost:8000/favicon.ico”
    如果(!(文件路径==“favicon.ico”)){
    file=fs.readFileSync(文件路径'utf-8')
    res.write(文件)
    }
    res.end();
    });
    服务器监听(8000);
    
    答案中的第一个链接做到了,而且非常简单:http server-s-a localhost-p 442-C certificate.pem-K privatekey.pem