简体   繁体   English

具有多个端点的Node.js应用程序

[英]Node.js Application with multiple endpoints

I have a node.js app that is just a library. 我有一个node.js应用程序,它只是一个库。 No I would like to provide different endpoints for that application. 不,我不想为该应用程序提供不同的端点。

I would like to have a web page via express I would like to have an admin command line (And for future maybe an Rest Api.) 我想通过express获得一个网页,我想拥有一个管理命令行(将来可能还会有一个Rest Api。)

So how would one structure a node.js app to exposes a website and an Admin Command Line Interface. 因此,如何构造一个node.js应用程序以公开一个网站和一个Admin Command Line Interface。 So that Admins can interact also with that application via command line at the same time. 这样,管理员就可以同时通过命令行与该应用程序进行交互。 The point is to connect to the running process and interact with it (production save). 关键是要连接到正在运行的流程并与之交互(保存生产)。

Since node is asynchronous, it has no problems listening to multiple endpoints simultaneously. 由于节点是异步的,因此同时侦听多个端点没有问题。 The structure of the program is basically just creating two servers (HTTP/Express/Socket/...), configured separately, and calling listen() on both. 该程序的结构基本上是创建两个服务器(HTTP / Express / Socket / ...),分别进行配置,然后在两个服务器上调用listen()。 As a quick and dirty example; 作为一个快速而肮脏的例子;

var http = require('http');
var net  = require('net');
var repl = require('repl');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World!\n');
}).listen(8081);

net.createServer(function (socket) {
  repl.start({
    prompt: "node> ", input: socket, output: socket
  }).on('exit', function() {
    socket.end();
  });
}).listen(8082);

...will listen on port 8081/HTTP with a message, and a REPL via telnet to 8082. ...将通过消息侦听端口8081 / HTTP,并通过telnet到8082进行REPL。

You can naturally choose to reuse methods/configuration, but that's your choice, not anything enforced by Node. 您自然可以选择重用方法/配置,但这是您的选择,而不是Node强制执行的任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM