node.js运行js
by Samer Buna
通过Samer Buna
Update: This article is now part of my book “Node.js Beyond The Basics”.
更新:这篇文章现在是我的书《超越基础的Node.js》的一部分。
Read the updated version of this content and more about Node at jscomplete.com/node-beyond-basics.
在jscomplete.com/node-beyond-basics中阅读此内容的更新版本以及有关Node的更多信息。
This article will challenge the very limits of your Node.js knowledge.
本文将挑战您的Node.js知识的极限。
I started learning Node.js shortly after Ryan Dahl first presented it, and I wasn’t able to answer a lot of the questions I ask in this article even a year ago. If you can truly answer all of these questions, then your knowledge of Node.js is beyond great. We should be friends.
在Ryan Dahl首次提出 Node.js之后不久,我就开始学习它。即使在一年前,我也无法回答我在本文中提出的许多问题。 如果您能真正回答所有这些问题,那么您对Node.js的了解将非常出色。 我们应该成为朋友。
The reason I think this challenge will take you by surprise is that many of us have been mostly learning Node the wrong way. Most tutorials, books, and courses about Node focus on the Node ecosystem — not the Node runtime itself. They focus on teaching what can be done with all the packages available for you when you work with Node, like Express and Socket.IO, rather than teaching the capabilities of the Node runtime itself.
我认为这一挑战会让您感到惊讶的原因是,我们中的许多人大多数都是以错误的方式学习Node。 有关Node的大多数教程,书籍和课程都专注于Node生态系统,而不是Node运行时本身。 他们专注于讲解使用Node时使用Express和Socket.IO等所有可用包可以做什么,而不是讲授Node运行时本身的功能。
There are good reasons for this. Node is raw and flexible. It doesn’t provide complete solutions, but rather provides a rich runtime that enables you to implement solutions of your own. Libraries like Express.js and Socket.IO are more of complete solutions, so it makes more sense to teach those libraries, so you can enable learners to use these complete solutions.
这有充分的理由。 节点是原始且灵活的。 它不提供完整的解决方案,而是提供了丰富的运行时,使您能够实施自己的解决方案。 诸如Express.js和Socket.IO之类的库更像是完整的解决方案,因此教那些库更有意义,因此您可以使学习者能够使用这些完整的解决方案。
The conventional wisdom seems to be that only those whose job is to write libraries like Express.js and Socket.IO need to understand everything about the Node.js runtime. But I think this is wrong. A solid understanding of the Node.js runtime itself is the best thing you can do before using those complete solutions. You should at least have the knowledge and confidence to judge a package by its code, so you can make an educated decision about using it.
传统的观点似乎是,只有那些致力于编写Express.js和Socket.IO之类的库的人才需要了解有关Node.js运行时的一切。 但是我认为这是错误的。 在使用那些完整的解决方案之前,最好能对Node.js运行时本身有深刻的了解。 您至少应具有知识和信心,可以根据其代码来判断软件包,以便就使用该软件包做出明智的决定。
This is why I decided to create a Pluralsight course fully dedicated to pure Node. While doing the research for the course, I put together a list of specific questions for you to determine whether your knowledge of the Node runtime is already strong enough, or if it could be improved.
这就是为什么我决定创建一个完全致力于纯Node的Pluralsight课程的原因。 在对该课程进行研究时,我整理了一系列具体问题供您确定您对Node运行时的知识是否已经足够强大,或者是否可以改进。
If you can answer most of these questions and you’re looking for a job, let me know! If on the other hand, most of these questions take you by surprise, you just need to make learning the Node runtime itself a priority. Your knowledge of that will make you a much more desirable developer.
如果您能回答其中大多数问题,并且正在寻找工作,请告诉我! 另一方面,如果大多数这些问题使您感到惊讶,那么您只需要使学习Node运行时本身成为优先事项即可。 您的知识将使您成为更理想的开发人员。
Some of these questions are short and easy while others require longer answers and deeper knowledge. They are all presented here in no particular order.
这些问题中的一些简短而容易,而另一些则需要更长的答案和更深的知识。 它们都以不特定的顺序显示在这里。
I know that you’re going to want answers after reading this list. The advice section below has some answers, but I’ll also be answering all of these questions in a series of freeCodeCamp articles after this one. But let me tease your knowledge first!
我知道您在阅读此列表后会想要答案。 下面的建议部分提供了一些答案,但是在此之后,我还将在一系列freeCodeCamp文章中回答所有这些问题。 但是,让我先梳理您的知识!
When exporting the API of a Node module, why can we sometimes use exports
and other times we have to use module.exports
?
当出口节点模块的API,为什么我们有时会用exports
,我们必须使用其他时间module.exports
?
What is the difference between setImmediate
and process.nextTick
?
setImmediate
和process.nextTick
什么区别?
What are the major differences between spawn
, exec
, and fork
?
spawn
, exec
和fork
之间的主要区别是什么?
What are the --harmony-*
flags?
什么是--harmony-*
标志?
What is process.argv
? What type of data does it hold?
什么是process.argv
? 它保存什么类型的数据?
What’s the problem with the process uncaughtException
event? How is it different than the exit
event?
流程uncaughtException
事件有什么问题? 与exit
事件有何不同?
What does the _
mean inside of Node’s REPL?
_
在REPL的REPL内部是什么意思?
What’s the difference between Buffer.alloc
and Buffer.allocUnsafe
?
Buffer.alloc
和Buffer.allocUnsafe
什么Buffer.allocUnsafe
?
How is the slice
method on buffers different from that on arrays?
缓冲区上的slice
方法与数组上有什么不同?
What is the string_decoder
module useful for? How is it different than casting buffers to strings?
string_decoder
模块有什么用? 与将缓冲区强制转换为字符串有何不同?
What is the main
property in package.json
useful for?
package.json
的main
属性有什么用?
When creating an http server and writing a response for a request, why is the end()
function required?
创建http服务器并为请求编写响应时,为什么需要end()
函数?
When is it ok to use the file system *Sync
methods?
什么时候可以使用文件系统*Sync
方法?
What is the node-gyp
package used for?
node-gyp
软件包用于什么用途?
The objects exports
, require
, and module
are all globally available in every module but they are different in every module. How?
对象exports
, require
和module
在每个模块中全局可用,但是在每个模块中它们都不同。 怎么样?
If you execute a node script file that has the single line: console.log(arguments);
, what exactly will node print?
如果执行的节点脚本文件只有一行: console.log(arguments);
,节点将打印什么内容?
How can a module be both requirable by other modules and executable directly using the node
command?
一个模块如何既可以被其他模块要求又可以使用node
命令直接执行?
What is the console.time
function useful for?
console.time
函数有什么用?
What does the --inspect
argument do for the node command?
--inspect
参数对节点命令有什么作用?
The require
function always caches the module it requires. What can you do if you need to execute the code in a required module many times?
require
函数始终缓存所需的模块。 如果需要多次在必需的模块中执行代码,该怎么办?
Learning Node.js can be challenging. Here are some of the guidelines that I hope will help along that journey:
学习Node.js可能具有挑战性。 以下是我希望在此过程中对您有所帮助的一些准则:
Node is a set of libraries on top of a VM engine which can compile JavaScript so it goes without saying that the important skills for JavaScript itself is a subset of the important skills for Node. You should start with JavaScript itself.
Node是在VM引擎之上的一组库,可以编译JavaScript,因此不用说JavaScript本身的重要技能就是Node重要技能的一部分。 您应该从JavaScript本身开始。
Do you understand functions, scopes, binding, this keyword, new keyword, closures, classes, module patterns, prototypes, callbacks, and promises? Are you aware of the various methods that can be used on Numbers, Strings, Arrays, Sets, Objects, and Maps? Getting yourself comfortable with the items on this list will make learning the Node API much easier. For example, trying to learn the ‘fs’ module methods before you have a good understanding of callbacks may lead to unnecessary confusion.
您是否了解函数, 范围 ,绑定,此关键字,新关键字, 闭包 ,类,模块模式,原型,回调和Promise? 您是否知道可以在数字,字符串,数组,集合,对象和映射上使用的各种方法? 使自己熟悉此列表中的项目将使学习Node API更加容易。 例如,在充分了解回调之前尝试学习'fs'模块方法可能会导致不必要的混乱。
Callbacks and promises (and generators/async patterns) are especially important for Node. You need to understand how asynchronous operations are first class in Node.
回调和承诺(以及生成器/异步模式)对于Node尤其重要。 您需要了解异步操作如何成为Node中的头等舱。
You can compare the non-blocking nature of lines of code in a Node program to the way you order a Starbucks coffee (in the store, not the drive-thru):
您可以将Node程序中代码行的非阻塞性质与订购星巴克咖啡的方式(在商店中,而不是直通车)进行比较:
Customize your order, no whipped cream for example | Give the function some arguments: ({whippedCream: false})
自定义您的订单,例如不加奶油| 给函数一些参数: ({whippedCream: false})
Give the Starbucks worker your name with the order | Give Node a callback with your function: ({whippedCream: false}, callback)
根据订单给星巴克员工您的名字| 使用您的函数为Node提供回调: ({whippedCream: false}, callback)
When your order is ready, the Starbucks worker will call your name and give you your order | When your function is computed and Node.js has a ready result for you, it’ll call your callback with that result: callback(result)
准备好您的订单后,星巴克工作人员会打电话给您,并给您您的订单| 计算函数并为Node.js准备好结果时,它将使用以下结果调用回调: callback(result)
I’ve written a blog post about this: Asynchronous Programming as Seen at Starbucks
我写了一篇关于此的博客文章: 星巴克所见的异步编程
There is a Stack, a Heap, and a Queue. You can read books on this subject and still not understand it completely, but I guarantee you’ll do if you watch this guy.
有一个堆栈,一个堆和一个队列。 您可以阅读有关此主题的书籍,但仍然不能完全理解它,但是我保证,如果您看到这个人,您也会这样做。
Philip explains the Event Loop that’s in the browser, but almost the exact same thing applies to Node.js (there are some differences).
Philip解释了浏览器中的事件循环,但是几乎完全相同的事情适用于Node.js(有一些区别)。
A Node process can be idle but it never sleeps. It keeps track of all the callbacks that are pending and if there is nothing left to execute it will simply exit. To keep a Node process running you can for example use a setInterval
function because that would create a permanent pending callback in the Event Loop.
Node进程可以处于空闲状态,但从不Hibernate。 它跟踪所有待处理的回调,如果没有什么要执行的,它将退出。 为了使Node进程保持运行状态,您可以使用例如setInterval
函数,因为这将在事件循环中创建永久的挂起回调。
They’re all defined on a global variable (which is usually compared to the window
variable in browsers). In a Node’s REPL, type global.
and hit tab to see all the items available (or simple double-tab on an empty line). Some of these items are JavaScript structures (like Array
and Object
). Some of them are Node library functions (like setTimeout
, or console
to print to stdout
/stderr
), and some of them are Node global objects that you can use for certain tasks (for example, process.env
can be used to read the host environment variables).
它们都是在全局变量上定义的(通常与浏览器中的window
变量进行比较)。 在节点的REPL中,键入global.
并点击选项卡以查看所有可用项(或在空行上单击简单的双选项卡)。 其中一些是JavaScript结构(例如Array
和Object
)。 其中一些是Node库函数(例如setTimeout
或用于打印到stdout
/ stderr
console
),其中一些是Node全局对象,可用于某些任务(例如, process.env
可用于读取主机)环境变量)。
You need to understand most of what you see in that list.
您需要了解该列表中的大部分内容。
Some of those will feel familiar, like Timers for example, because they also exist in the browser and Node is simulating that environment. However, there is much more to learn, like fs
, path
, readline
, http
, net
, stream
, cluster
, ... (The auto-complete list above has them all).
其中一些会感到熟悉,例如Timers ,因为它们也存在于浏览器中,并且Node正在模拟该环境。 但是,还有更多的东西要学习,例如fs
, path
, readline
, http
, net
, stream
, cluster
,...(上面的自动完成列表包含所有这些)。
For example, you can read/write files with fs
, you can run a streaming-ready web server using “http
”, and you can run a tcp server and program sockets with “net
”. Node today is so much more powerful than it was just a year ago, and it’s getting better by the commit. Before you look for a package to do some task, make sure that you can’t do that task with the built-in Node packages first.
例如,您可以使用fs
读取/写入文件,可以使用“ http
”运行支持流式传输的Web服务器,还可以使用“ net
”运行tcp服务器和程序套接字。 今天的Node比一年前强大得多,并且通过提交变得越来越好。 寻找程序包执行某些任务之前,请确保首先无法使用内置的Node程序包执行该任务。
The events
library is especially important because most of Node architecture is event-driven.
events
库尤其重要,因为大多数Node架构都是事件驱动的。
There’s always more that you can learn about the Node API, so keep expanding your horizons.
您可以从中获得更多有关Node API的知识 ,因此请继续拓展自己的视野。
You build simple single-process building blocks (nodes) that can be organized with good networking protocols to have them communicate with each other and scale up to build large distributed programs. Scaling a Node application is not an afterthought — it’s built right into the name.
您可以构建简单的单进程构建块(节点),可以使用良好的网络协议对其进行组织,以使它们彼此通信并扩展以构建大型分布式程序。 扩展Node应用程序不是事后的想法-它内置在名称中。
Pick a framework, like Express, and try to understand some of its code. Ask specific questions about the things you don’t understand. I try to answer questions on the jsComplete slack channel when I can.
选择一个框架,例如Express,并尝试了解其一些代码。 询问有关您不了解的事物的特定问题。 我会尽可能尝试在jsComplete松弛频道上回答问题。
Finally, write a web application in Node without using any frameworks. Try to handle as many cases as you can, respond with an HTML file, parse query strings, accept form input, and create an endpoint that responds with JSON.
最后,在不使用任何框架的情况下在Node中编写一个Web应用程序。 尝试处理尽可能多的情况,使用HTML文件进行响应,解析查询字符串,接受表单输入,并创建使用JSON进行响应的终结点。
Also try writing a chat server, publishing an npm package, and contributing to an open-source Node-based project.
还可以尝试编写聊天服务器,发布npm程序包,并为基于Node的开源项目做出贡献。
Good luck! Thanks for reading.
祝好运! 谢谢阅读。
Learning React or Node? Checkout my books:
学习React还是Node? 结帐我的书:
node.js运行js