当第一个应用程序显示此行时,我现在找到了很多来源
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}).listen(8080);
只是极客,我的问题是为什么我们需要服务器/端口来监听 Node js 应用程序的请求? 为什么我们不能以 localhost/application_name 运行? 为什么我们需要它?
有人可以详细说明一下吗?
最佳答案
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
因此,如果您想要一个仅适用于 bash 的应用程序,则不需要任何 http 模块。
浏览器使用 HTTP。因此,如果您想开发网络应用程序,您需要使用该协议(protocol)。如果您在 80 端口上运行项目,您可以像 localhost/my_application 一样使用它。
简单的app.js
var result = doSomething();
functions doSomething(){
return "This the result";
}
console.log(result);
您可以从 bash 调用它。 Node app.js
。但它只是工作然后停止。
但是如果您想将此结构提供给 WWW(使用 HTTP),您需要创建服务器。 http
是一个很棒且简单的模块,用于使用 Node.js 创建服务器。
您可以使用 require
来使用其他 js 文件。
app.js
var result = doSomething();
functions doSomething(){
return "This the result";
}
module.exports = result;
服务器.js
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var result = require('app.js');
res.end(result);
}).listen(80);
现在您可以运行您的服务器了。 Node server.js
关于javascript - 为什么我们需要安装 http 模块来运行我们的 Node js 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47173930/