Javascript 如何决定何时使用 Node.js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5062614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:28:16  来源:igfitidea点击:

How to decide when to use Node.js?

javascriptnode.jsweb-applications

提问by Legend

I am new to this kind of stuff, but lately I've been hearing a lot about how good Node.jsis. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like Bitly- takes some content, archives it.

我是这种东西的新手,但最近我听到了很多关于Node.js有多好的消息。考虑到我通常非常喜欢使用 jQuery 和 JavaScript,我不禁想知道如何决定何时使用 Node.js。我想到的 Web 应用程序类似于Bitly- 获取一些内容,将其存档。

From all the homework I have been doing in the last few days, I obtained the following information. Node.js

从我这几天做的所有作业中,我获得了以下信息。节点.js

  • is a command-line tool that can be run as a regular web server and lets one run JavaScript programs
  • utilizes the great V8 JavaScript engine
  • is very good when you need to do several things at the same time
  • is event-based so all the wonderful Ajax-like stuff can be done on the server side
  • lets us share code between the browser and the backend
  • lets us talk with MySQL
  • 是一种命令行工具,可以作为常规的 Web 服务器运行,并可以运行 JavaScript 程序
  • 利用强大的V8 JavaScript 引擎
  • 当你需要同时做几件事时非常好
  • 是基于事件的,所以所有美妙的类似 Ajax的东西都可以在服务器端完成
  • 让我们在浏览器和后端之间共享代码
  • 让我们来谈谈 MySQL

Some of the sources that I have come across are:

我遇到的一些来源是:

Considering that Node.js can be run almost out-of-the-box on Amazon's EC2instances, I am trying to understand what type of problems require Node.js as opposed to any of the mighty kings out there like PHP, Pythonand Ruby. I understand that it really depends on the expertise one has on a language, but my question falls more into the general category of: When to use a particular framework and what type of problems is it particularly suited for?

考虑到 Node.js 几乎可以在Amazon 的 EC2实例上开箱即用,我试图了解什么类型的问题需要 Node.js,而不是像PHPPythonRuby这样的任何强大的王者. 我知道这实际上取决于一个人对一种语言的专业知识,但我的问题更多地属于以下一般类别:何时使用特定框架以及它特别适合什么类型的问题?

采纳答案by Benson

You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as "long-polling", you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like Ruby on Railsor Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpitattack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.

您在总结 Node.js 的优点方面做得很好。我的感觉是 Node.js 特别适合您希望保持从浏览器到服务器的持久连接的应用程序。使用称为“长轮询”的技术,您可以编写一个向用户实时发送更新的应用程序。在许多网络巨头上进行长轮询,例如Ruby on RailsDjango,会在服务器上产生巨大的负载,因为每个活动的客户端都会占用一个服务器进程。这种情况相当于一个tarpit攻击。当你使用 Node.js 之类的东西时,服务器不需要为每个打开的连接维护单独的线程。

This means you can create a browser-based chat applicationin Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.

这意味着您可以在 Node.js 中创建一个基于浏览器的聊天应用程序,它几乎不占用系统资源来为大量客户端提供服务。任何时候你想要进行这种长轮询,Node.js 都是一个不错的选择。

It's worth mentioning that Ruby and Python both have tools to do this sort of thing (eventmachineand twisted, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty.

值得一提的是,Ruby 和 Python 都有做这种事情的工具(分别是eventmachinetwisted),但 Node.js 做得非常好,而且从头开始。JavaScript 非常适合基于回调的并发模型,它在这方面表现出色。此外,能够使用客户端和服务器本地的 JSON 进行序列化和反序列化非常漂亮。

I look forward to reading other answers here, this is a fantastic question.

我期待在这里阅读其他答案,这是一个很棒的问题。

It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The Meteor frameworkmakes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back.

值得指出的是,Node.js 也非常适合在客户端/服务器之间重用大量代码的情况。该流星框架使得这个非常容易,而且很多人都暗示这可能是网络发展的未来。我可以从经验中说,在 Meteor 中编写代码非常有趣,其中很大一部分是花更少的时间思考如何重构数据,因此在浏览器中运行的代码可以很容易地操纵它并将其传回。

Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: TicTacToe and Long Polling with Pyramid.

这是一篇关于 Pyramid 和长轮询的文章,结果证明在 gevent 的帮助下很容易设置:TicTacToe 和 Long Polling with Pyramid

回答by fisherwebdev

I believe Node.js is best suited for real-time applications: online games, collaboration tools, chat rooms, or anything where what one user (or robot? or sensor?) does with the application needs to be seen by other users immediately, without a page refresh.

我相信 Node.js 最适合实时应用:在线游戏、协作工具、聊天室,或者任何一个用户(或机器人?或传感器?)对应用程序所做的事情需要其他用户立即看到的任何东西,没有页面刷新。

I should also mention that Socket.IO in combination with Node.js will reduce your real-time latency even further than what is possible with long polling. Socket.IO will fall back to long polling as a worst case scenario, and instead use web sockets or even Flash if they are available.

我还应该提到,与长轮询相比,Socket.IO 与 Node.js 相结合将进一步减少您的实时延迟。作为最坏的情况,Socket.IO 将回退到长轮询,而是使用 Web 套接字甚至 Flash(如果它们可用)。

But I should also mention that just about any situation where the code might block due to threads can be better addressed with Node.js. Or any situation where you need the application to be event-driven.

但我还应该提到,几乎任何代码可能因线程而阻塞的情况都可以使用 Node.js 更好地解决。或者您需要应用程序是事件驱动的任何情况。

Also, Ryan Dahl said in a talk that I once attended that the Node.js benchmarks closely rival Nginx for regular old HTTP requests. So if we build with Node.js, we can serve our normal resources quite effectively, and when we need the event-driven stuff, it's ready to handle it.

此外,Ryan Dahl 在一次演讲中说,我曾经参加过,Node.js 基准测试与 Nginx 在常规旧 HTTP 请求方面非常相似。因此,如果我们使用 Node.js 构建,我们可以非常有效地为我们的普通资源提供服务,并且当我们需要事件驱动的东西时,它已准备好处理它。

Plus it's all JavaScript all the time. Lingua Franca on the whole stack.

此外,它一直都是 JavaScript。整个堆栈中的通用语。

回答by joeytwiddle

Reasons to use NodeJS:

使用 NodeJS 的原因:

  • It runs Javascript, so you can use the same languageon server and client, and even share some code between them (e.g. for form validation, or to render views at either end.)

  • The single-threadedevent-driven system is fasteven when handling lots of requests at once, and also simple, compared to traditional multi-threaded Javaor ROR frameworks.

  • The ever-growing pool of packagesaccessible through NPM, including client and server-side libraries/modules, as well as command-line tools for web development. Most of these are conveniently hosted on github, where sometimes you can report an issue and find it fixed within hours! It's nice to have everything under one roof, with standardized issue reporting and easy forking.

  • It has become the defacto standard environment in which to run Javascript-related toolsand other web-related tools, including task runners, minifiers, beautifiers, linters, preprocessors, bundlers and analytics processors.

  • It seems quite suitable for prototyping, agile development and rapid product iteration.

  • 它运行 Javascript,因此您可以在服务器和客户端使用相同的语言,甚至可以在它们之间共享一些代码(例如用于表单验证,或在任一端呈现视图。)

  • 单线程事件驱动系统是快速甚至还可以同时处理大量的请求时,也简单,相比传统的多线程的Java或ROR框架。

  • 可通过 NPM 访问的不断增长的软件包池,包括客户端和服务器端库/模块,以及用于 Web 开发的命令行工具。其中大部分都方便地托管在 github 上,有时您可以在那里报告问题并在数小时内找到修复!很高兴将所有内容都集中在一个屋檐下,具有标准化的问题报告和易于分叉。

  • 它已成为运行Javascript 相关工具和其他Web 相关工具(包括任务运行器、缩小器、美化器、linter、预处理器、捆绑器和分析处理器)的事实上的标准环境。

  • 它似乎非常适合原型设计、敏捷开发和快速产品迭代

Reasons notto use NodeJS:

使用 NodeJS 的原因:

  • It runs Javascript, which has no compile-time type checking. For large, complex safety-criticalsystems, or projects including collaboration between different organizations, a language which encourages contractual interfacesand provides static type checkingmay save you some debugging time (and explosions) in the long run. (Although the JVM is stuck with null, so please use Haskell for your nuclear reactors.)

  • Added to that, many of the packages in NPM are a little raw, and still under rapid development. Some libraries for older frameworks have undergone a decade of testing and bugfixing, and are very stableby now. Npmjs.org has no mechanism to rate packages, which has lead to a proliferation of packages doing more or less the same thing, out of which a large percentage are no longer maintained.

  • Nested callback hell. (Of course there are 20 different solutionsto this...)

  • The ever-growing pool of packages can make one NodeJS project appear radically differentfrom the next. There is a large diversity in implementations due to the huge number of options available (e.g. Express/Sails.js/Meteor/Derby). This can sometimes make it harder for a new developer to jump in on a Node project. Contrast that with a Railsdeveloper joining an existing project: he should be able to get familiar with the app pretty quickly, because all Rails apps are encouraged to use a similar structure.

  • Dealing with files can be a bit of a pain. Things that are trivial in other languages, like reading a line from a text file, are weird enough to do with Node.jsthat there's a StackOverflow question on that with 80+ upvotes. There's no simple way to read one record at a time from a CSV file. Etc.

  • 它运行 Javascript,它没有编译时类型检查。对于大型、复杂的安全关键系统,或包括不同组织之间协作的项目,从长远来看,鼓励契约接口并提供静态类型检查的语言可能会为您节省一些调试时间(和爆炸)。(虽然 JVM 被卡住了null,所以请为你的核反应堆使用 Haskell。)

  • 除此之外,NPM 中的许多包都有些原始,并且仍在快速开发中。一些旧框架的库已经经历了十年的测试和错误修复,现在非常稳定Npmjs.org 没有对包进行评级的机制,这导致了或多或少做相同事情的包的激增,其中很大一部分不再维护。

  • 嵌套回调地狱。(当然,对此有20 种不同的解决方案......)

  • 不断增长的包池可以使一个 NodeJS 项目看起来与下一个完全不同。由于可用的选项数量众多(例如 Express/ Sails.js/ Meteor/ Derby),实现方式存在很大差异。这有时会使新开发人员更难加入 Node 项目。与加入现有项目的Rails开发人员形成对比:他应该能够很快熟悉应用程序,因为鼓励所有 Rails 应用程序使用类似的结构

  • 处理文件可能有点痛苦。在其他语言中微不足道的事情,比如从文本文件中读取一行,对于Node.js来说很奇怪,以至于有一个 StackOverflow 问题,有 80 多个赞成票。有没有简单的方法从一个CSV文件一次读取一个记录。等等。

I love NodeJS, it is fast and wild and fun, but I am concerned it has little interest in provable-correctness. Let's hope we can eventually merge the best of both worlds. I am eager to see what will replace Node in the future... :)

我喜欢 NodeJS,它快速、狂野且有趣,但我担心它对可证明的正确性没有兴趣。让我们希望我们最终能够融合两全其美。我很想知道将来什么会取代 Node... :)

回答by stewe

To make it short:

简而言之:

Node.js is well suited for applications that have a lot of concurrent connections and each request only needs very few CPU cycles, because the event loop (with all the other clients) is blocked during execution of a function.

Node.js 非常适合具有大量并发连接且每个请求只需要很少 CPU 周期的应用程序,因为事件循环(与所有其他客户端)在函数执行期间被阻塞。

A good article about the event loop in Node.js is Mixu's tech blog: Understanding the node.js event loop.

一篇关于 Node.js 事件循环的好文章是Mixu 的技术博客:了解 node.js 事件循环

回答by Joonas

I have one real-world example where I have used Node.js. The company where I work got one client who wanted to have a simple static HTML website. This website is for selling one item using PayPaland the client also wanted to have a counter which shows the amount of sold items. Client expected to have huge amount of visitors to this website. I decided to make the counter using Node.js and the Express.jsframework.

我有一个使用 Node.js 的真实示例。我工作的公司有一个客户想要拥有一个简单的静态 HTML 网站。该网站用于使用PayPal销售一件商品,客户还希望有一个显示已售商品数量的计数器。客户预计本网站将有大量访问者。我决定使用 Node.js 和Express.js框架制作计数器。

The Node.js application was simple. Get the sold items amount from a Redisdatabase, increase the counter when item is sold and serve the counter value to users via the API.

Node.js 应用程序很简单。从Redis数据库中获取已售商品数量,在商品售出时增加计数器,并通过API将计数器值提供给用户。

Some reasons why I chose to use Node.js in this case

在这种情况下我选择使用 Node.js 的一些原因

  1. It is very lightweight and fast. There has been over 200000 visits on this website in three weeks and minimal server resources has been able to handle it all.
  2. The counter is really easy to make to be real time.
  3. Node.js was easy to configure.
  4. There are lots of modules available for free. For example, I found a Node.js module for PayPal.
  1. 它非常轻巧且快速。该网站在三周内的访问量已超过 200000 次,最少的服务器资源已经能够处理这一切。
  2. 计数器真的很容易成为实时的。
  3. Node.js 很容易配置。
  4. 有很多模块可以免费使用。例如,我发现了一个用于 PayPal 的 Node.js 模块。

In this case, Node.js was an awesome choice.

在这种情况下,Node.js 是一个很棒的选择。

回答by Tony O'Hagan

The most important reasons to start your next project using Node ...

使用 Node 开始下一个项目的最重要原因......

  • All the coolest dudes are into it ... so it mustbe fun.
  • You can hangout at the cooler and have lots of Node adventures to brag about.
  • You're a penny pincher when it comes to cloud hosting costs.
  • Been there done that with Rails
  • You hate IIS deployments
  • Your old IT job is getting rather dull and you wish you were in a shiny new Start Up.
  • 所有最酷的家伙都喜欢它......所以它一定很有趣。
  • 你可以在凉爽的地方聚会,并有很多 Node 冒险可以吹嘘。
  • 当涉及到云托管成本时,您是一个吝啬鬼。
  • 在那里用 Rails 做过
  • 你讨厌 IIS 部署
  • 你的旧 IT 工作变得相当乏味,你希望自己处于一个闪亮的新启动阶段。

What to expect ...

期待什么...

  • You'll feel safe and secure with Express without all the server bloatware you never needed.
  • Runs like a rocket and scales well.
  • You dream it. You installed it. The node package repo npmjs.orgis the largest ecosystem of open source libraries in the world.
  • Your brain will get time warped in the land of nested callbacks ...
  • ... until you learn to keep your Promises.
  • Sequelizeand Passportare your new API friends.
  • Debugging mostly async code will get umm ... interesting.
  • Time for all Noders to master Typescript.
  • 使用 Express,您会感到安全可靠,而无需安装您从未需要的所有服务器膨胀软件。
  • 像火箭一样运行并且扩展性很好。
  • 你梦想它。你安装了它。节点包 repo npmjs.org是世界上最大的开源库生态系统。
  • 你的大脑会在嵌套回调的土地上时间扭曲......
  • ...直到你学会遵守你的承诺
  • SequelizePassport是您的 API 新朋友。
  • 调试主要是异步代码会得到嗯...有趣
  • 是时候让所有 Noders 掌握Typescript 了

Who uses it?

谁使用它?

  • PayPal, Netflix, Walmart, LinkedIn, Groupon, Uber, GoDaddy, Dow Jones
  • Here's why they switched to Node.
  • PayPal、Netflix、沃尔玛、LinkedIn、Groupon、优步、GoDaddy、道琼斯
  • 这就是他们切换到 Node的原因。

回答by Ajay Tiwari

There is nothing like Silver Bullet. Everything comes with some cost associated with it. It is like if you eat oily food, you will compromise your health and healthy food does not come with spices like oily food. It is individual choice whether they want health or spices as in their food. Same way Node.js consider to be used in specific scenario. If your app does not fit into that scenario you should not consider it for your app development. I am just putting my thought on the same:

没有什么能比得上 Silver Bullet。一切都伴随着一些与之相关的成本。就好像你吃油腻的食物,你会损害你的健康,而健康的食物不像油性食物那样带有香料。他们想要健康还是想要食物中的香料,这是个人的选择。Node.js 考虑在特定场景中使用的方式相同。如果您的应用程序不适合该场景,则不应在应用程序开发中考虑它。我只是把我的想法放在同样的地方:

When to use Node.JS

何时使用 Node.JS

  1. If your server side code requires very few cpu cycles. In other world you are doing non blocking operation and does not have heavy algorithm/Job which consumes lots of CPU cycles.
  2. If you are from Javascript back ground and comfortable in writing Single Threaded code just like client side JS.
  1. 如果您的服务器端代码需要很少的 CPU 周期。在其他世界中,您正在执行非阻塞操作,并且没有消耗大量 CPU 周期的繁重算法/作业。
  2. 如果您来自 Javascript 背景并且喜欢像客户端 JS 一样编写单线程代码。

When NOT to use Node.JS

何时不使用 Node.JS

  1. Your server request is dependent on heavy CPU consuming algorithm/Job.
  1. 您的服务器请求依赖于大量消耗 CPU 的算法/作业。

Scalability Consideration with Node.JS

Node.JS 的可扩展性考虑

  1. Node.JS itself does not utilize all core of underlying system and it is single threaded by default, you have to write logic by your own to utilize multi core processor and make it multi threaded.
  1. Node.JS 本身并没有利用底层系统的所有核心,它默认是单线程的,你必须自己编写逻辑才能使用多核处理器并使其成为多线程。

Node.JS Alternatives

Node.JS 替代品

There are other option to use in place of Node.JS however Vert.xseems to be pretty promising and has lots of additional features like polygot and better scalability considerations.

还有其他选项可以代替 Node.JS,但是Vert.x似乎很有前途,并且具有许多附加功能,例如 polygot 和更好的可扩展性考虑。

回答by BoxerBucks

Another great thing that I thinkno one has mentioned about Node.js is the amazing community, the package management system (npm) and the amount of modules that exist that you can include by simply including them in your package.json file.

我认为没有人提到 Node.js 的另一件好事是令人惊叹的社区、包管理系统 (npm) 和现有模块的数量,您只需将它们包含在 package.json 文件中即可。

回答by shash7

My piece: nodejs is great for making real time systems like analytics, chat-apps, apis, ad servers, etc. Hell, I made my first chat app using nodejs and socket.io under 2 hours and that too during exam week!

我的作品:nodejs 非常适合制作实时系统,如分析、聊天应用程序、api、广告服务器等。地狱,我在 2 小时内使用 nodejs 和 socket.io 制作了我的第一个聊天应用程序,在考试周期间也是如此!

Edit

编辑

Its been several years since I have started using nodejs and I have used it in making many different things including static file servers, simple analytics, chat apps and much more. This is my take on when to use nodejs

自从我开始使用 nodejs 已经好几年了,我已经用它制作了许多不同的东西,包括静态文件服务器、简单的分析、聊天应用程序等等。这是我对何时使用 nodejs 的看法

When to use

何时使用

When making system which put emphasis on concurrency and speed.

在制作强调并发性和速度的系统时。

  • Sockets only servers like chat apps, irc apps, etc.
  • Social networks which put emphasis on realtime resources like geolocation, video stream, audio stream, etc.
  • Handling small chunks of data really fast like an analytics webapp.
  • As exposing a REST only api.
  • 仅套接字服务器,如聊天应用程序、irc 应用程序等。
  • 社交网络强调实时资源,如地理定位、视频流、音频流等。
  • 像分析网络应用程序一样快速处理小块数据。
  • 作为公开 REST only api。

When not to use

何时不使用

Its a very versatile webserver so you can use it wherever you want but probably not these places.

它是一个非常通用的网络服务器,所以你可以在任何你想要的地方使用它,但可能不是这些地方。

  • Simple blogs and static sites.
  • Just as a static file server.
  • 简单的博客和静态网站。
  • 就像一个静态文件服务器。

Keep in mind that I am just nitpicking. For static file servers, apache is better mainly because it is widely available. The nodejs community has grown larger and more mature over the years and it is safe to say nodejs can be used just about everywhere if you have your own choice of hosting.

请记住,我只是吹毛求疵。对于静态文件服务器,apache 更好,主要是因为它广泛可用。多年来,nodejs 社区变得越来越大、越来越成熟,可以肯定地说,如果您有自己的托管选择,nodejs 几乎可以在任何地方使用。

回答by Vinayak Bevinakatti

It can be used where

它可以用于

  • Applications that are highly event driven & are heavily I/O bound
  • Applications handling a large number of connections to other systems
  • Real-time applications (Node.js was designed from the ground up for real time and to be easy to use.)
  • Applications that juggle scads of information streaming to and from other sources
  • High traffic, Scalable applications
  • Mobile apps that have to talk to platform API & database, without having to do a lot of data analytics
  • Build out networked applications
  • Applications that need to talk to the back end very often
  • 高度事件驱动和高度 I/O 绑定的应用程序
  • 处理与其他系统的大量连接的应用程序
  • 实时应用程序(Node.js 的设计初衷是为了实时且易于使用。)
  • 处理进出其他来源的大量信息流的应用程序
  • 高流量、可扩展的应用程序
  • 必须与平台 API 和数据库通信的移动应用程序,而无需进行大量数据分析
  • 构建网络应用程序
  • 需要经常与后端通信的应用程序

On Mobile front, prime-time companies have relied on Node.js for their mobile solutions. Check out why?

在移动方面,黄金时段的公司依赖 Node.js 来提供他们的移动解决方案。看看为什么?

LinkedInis a prominent user. Their entire mobile stack is built on Node.js. They went from running 15 servers with 15 instances on each physical machine, to just 4 instances – that can handle double the traffic!

LinkedIn是一个突出的用户。他们的整个移动堆栈都建立在 Node.js 之上。他们从在每台物理机器上运行 15 个服务器和 15 个实例,变成了只有 4 个实例——可以处理两倍的流量!

eBaylaunched ql.io, a web query language for HTTP APIs, which uses Node.js as the runtime stack. They were able to tune a regular developer-quality Ubuntu workstation to handle more than 120,000 active connections per node.js process, with each connection consuming about 2kB memory!

eBay推出了 ql.io,一种用于 HTTP API 的 Web 查询语言,它使用 Node.js 作为运行时堆栈。他们能够调整一个常规的开发人员质量的 Ubuntu 工作站,以处理每个 node.js 进程超过 120,000 个活动连接,每个连接消耗大约 2kB 内存!

Walmartre-engineered its mobile app to use Node.js and pushed its JavaScript processing to the server.

沃尔玛重新设计了其移动应用程序以使用 Node.js,并将其 JavaScript 处理推送到服务器。

Read more at: http://www.pixelatingbits.com/a-closer-look-at-mobile-app-development-with-node-js/

阅读更多信息:http: //www.pixelatingbits.com/a-closer-look-at-mobile-app-development-with-node-js/