├── docs ├── .nojekyll ├── CNAME ├── _navbar.md ├── img │ ├── nodejs_eventlop.jpg │ ├── node-hello-world.png │ ├── javascript_eventloop.jpg │ └── test_pyramid_for_node_js_unit_testing-1465216863453.png ├── zh │ ├── test.md │ ├── module.md │ ├── README.md │ ├── common.md │ ├── event-async.md │ └── process-threads.md ├── en │ ├── test.md │ ├── README.md │ ├── event-async.md │ ├── process-threads.md │ └── common.md └── index.html ├── _config.yml ├── LICENSE ├── .gitignore └── README.md /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/CNAME: -------------------------------------------------------------------------------- 1 | interview.nodejs.red -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /docs/_navbar.md: -------------------------------------------------------------------------------- 1 | - Translations 2 | - [:uk: English](/) 3 | - [:cn: 中文](/zh/) 4 | -------------------------------------------------------------------------------- /docs/img/nodejs_eventlop.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qufei1993/Nodejs-Interview-Questions/HEAD/docs/img/nodejs_eventlop.jpg -------------------------------------------------------------------------------- /docs/img/node-hello-world.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qufei1993/Nodejs-Interview-Questions/HEAD/docs/img/node-hello-world.png -------------------------------------------------------------------------------- /docs/img/javascript_eventloop.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qufei1993/Nodejs-Interview-Questions/HEAD/docs/img/javascript_eventloop.jpg -------------------------------------------------------------------------------- /docs/img/test_pyramid_for_node_js_unit_testing-1465216863453.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qufei1993/Nodejs-Interview-Questions/HEAD/docs/img/test_pyramid_for_node_js_unit_testing-1465216863453.png -------------------------------------------------------------------------------- /docs/zh/test.md: -------------------------------------------------------------------------------- 1 | # 测试 2 | 3 | ## Q1: 什么是测试金字塔? 请给一个例子! 4 | 5 | 测试金字塔描述了你应该编写的单元测试、集成测试和端到端测试所占用的比例。 6 | 7 |  8 | 9 | 一个测试 HTTP API 的示例,如下所示: 10 | 11 | * 金字塔的最底端所展示的有很多单元测试,用于分别测试各个模块(依赖项是 stub)。 12 | 13 | * 较少的集成测试,可以让你检查各模块之间的交互 (依赖项不是 stub)。 14 | * 更少的端到端测试,去调用你的实际接口(依赖项不是 stub)。 15 | 16 | ## Q2: 什么是 Stub?用一个例子说明 17 | 18 | Stubs 是模拟组件或模块的行为。在一个测试用例期间 Stub 可以用来模拟函数调用的返回值,还可以配合断言来使用。 19 | 20 | 例如,我们有一个读取文件的程序,在做测试时我们并不需要真正的去读,可以通过 Stub 进行模式。示例如下: 21 | 22 | ```js 23 | var fs = require('fs'); 24 | 25 | var readFileStub = sinon.stub(fs, 'readFile', function (path, cb) { 26 | return cb(null, 'filecontent'); 27 | }); 28 | 29 | expect(readFileStub).to.be.called; 30 | readFileStub.restore(); 31 | ``` -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 五月君 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | -------------------------------------------------------------------------------- /docs/en/test.md: -------------------------------------------------------------------------------- 1 | # Test 2 | 3 | ## Q1: What's a test pyramid? Give an example! 4 | 5 | A test pyramid describes the ratio of how many unit tests, integration tests and end-to-end test you should write. 6 | 7 |  8 | 9 | An example for an HTTP API may look like this: 10 | 11 | lots of low-level unit tests for models (dependencies are stubbed), 12 | fewer integration tests, where you check how your models interact with each other (dependencies are not stubbed), 13 | less end-to-end tests, where you call your actual endpoints (dependencies are not stubbed). 14 | 15 | Source: [https://blog.risingstack.com/node-js-interview-questions/](https://blog.risingstack.com/node-js-interview-questions/) 16 | 17 | ## Q2: What's a stub? Name a use case. 18 | 19 | Stubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called. 20 | 21 | A use-case can be a file read, when you do not want to read an actual file: 22 | 23 | ```js 24 | var fs = require('fs'); 25 | 26 | var readFileStub = sinon.stub(fs, 'readFile', function (path, cb) { 27 | return cb(null, 'filecontent'); 28 | }); 29 | 30 | expect(readFileStub).to.be.called; 31 | readFileStub.restore(); 32 | ``` 33 | 34 | Source: [https://blog.risingstack.com/node-js-interview-questions/](https://blog.risingstack.com/node-js-interview-questions/) 35 | -------------------------------------------------------------------------------- /docs/zh/module.md: -------------------------------------------------------------------------------- 1 | # 模块 2 | 3 | ## Q1:require 的加载机制? 4 | 5 | 在 Nodejs 中模块加载一般会经历3个步骤,路径分析、文件定位、编译执行。初次加载之后会进行缓存,下次直接从系统缓存加载。更多内容参考 [Node.js 模块加载机制](https://www.nodejs.red/#/nodejs/module?id=%e6%a8%a1%e5%9d%97%e5%8a%a0%e8%bd%bd%e6%9c%ba%e5%88%b6) 6 | 7 | ## Q2:module.exports 与 exports 的区别? 8 | 9 | exports 相当于 module.exports 的快捷方式如下所示: 10 | 11 | ```js 12 | const exports = modules.exports; 13 | ``` 14 | 15 | 但是要注意不能改变 exports 的指向,我们可以通过 exports.test = 'a' 这样来导出一个对象, 但是不能向下面示例直接赋值,这样会改变 exports 的指向,相当于修改了其引用关系。 16 | 17 | ```js 18 | // 错误的写法 将会得到 undefined 19 | exports = { 20 | 'a': 1, 21 | 'b': 2 22 | } 23 | 24 | // 正确的写法 25 | modules.exports = { 26 | 'a': 1, 27 | 'b': 2 28 | } 29 | ``` 30 | 31 | ## Q3:假设有 a.js、b.js 两个模块相互引用,会有什么问题?是否为陷入死循环? 32 | 33 | 两个模块相互引用,假设 a、b 两个模块,在 a 模块中应用了 b 模块,之后 b 模块又引用了 a 模块,那么后一个模块引用的是前一个模块未完成的副本,并不会导致死循环,看一下示例: 34 | 35 | ```js 36 | // a.js 37 | console.log('a模块start'); 38 | 39 | exports.test = 1; 40 | 41 | undeclaredVariable = 'a模块未声明变量' 42 | 43 | const b = require('./b'); 44 | 45 | console.log('a模块加载完毕: b.test值:',b.test); 46 | ``` 47 | 48 | ```js 49 | // b.js 50 | console.log('b模块start'); 51 | 52 | exports.test = 2; 53 | 54 | const a = require('./a'); 55 | 56 | console.log('undeclaredVariable: ', undeclaredVariable); 57 | 58 | console.log('b模块加载完毕: a.test值:', a.test); 59 | ``` 60 | 61 | 控制台执行 ```node a.js``` 查看输出结果: 62 | 63 | ```bash 64 | a模块start 65 | b模块start 66 | undeclaredVariable: a模块未声明变量 67 | b模块加载完毕: a.test值: 1 68 | a模块加载完毕: b.test值: 2 69 | ``` 70 | 71 | 启动 ```a.js``` 的时候,会加载 ```b.js```,那么在 ```b.js``` 中又加载了 ```a.js```,但是此时 ```a.js``` 模块还没有执行完,返回的是一个 ```a.js``` 模块的 ```exports``` 对象 ```未完成的副本``` 给到 ```b.js``` 模块。然后 ```b.js``` 完成加载之后将 ```exports``` 对象提供给了 ```a.js``` 模块 -------------------------------------------------------------------------------- /docs/zh/README.md: -------------------------------------------------------------------------------- 1 | # Nodejs-Interview-Questions 2 | 3 | 这是一份包含 Node.js 学习与面试的问题列表,我会定期的更新本仓库,也欢迎您提交一些 PR 或者一些好的建议!希望能对您的学习与工作有所帮助,Good luck ❤️ 4 | 5 | 如果您想更全面的学习 Node.js 技术栈,为您推荐开源项目 [Nodejs-Roadmap](https://www.nodejs.red) 6 | 7 | * 语言: [:cn: 中文](/zh/) | [:uk: English](/en/) 8 | * 预览: [https://interview.nodejs.red](https://interview.nodejs.red) 9 | 10 | > 作者: 五月君,Node.js Developer,[慕课网认证作者](https://www.imooc.com/u/2667395)。 11 | 12 | ## [基础](/zh/common.md) 13 | 14 | > 这个模块将会描述一些基础的或者通用的问题。 15 | 16 | * ```[Question1]``` 什么是 Node.js? 17 | * ```[Question2]``` 如何安装 Node.js? 18 | * ```[Question3]``` 如何用 Node.js 监听 80 端口? 19 | * ```[Question4]``` 什么是错误优先的回调函数? 20 | * ```[Question5]``` 你可以在 Node.js 中创建 Http 服务吗?通过代码来展示 21 | * ```[Question6]``` Node.js 的核心组件有哪些? 22 | * ```[Question7]``` 什么是“回调地狱”及如何避免它? 23 | * ```[Question8]``` 什么是 Node.js 的事件驱动编程? 24 | * ```[Question9]``` 什么是 NPM? 在 Node.js 中什么时候需要 NPM? 25 | * ```[Question10]``` Node.js 可以做什么? 10 个 Node.js 的应用场景? 26 | 27 | [阅读更多](/zh/common.md) 28 | 29 | ## [模块](/zh/module.md) 30 | 31 | * ```[Question1]``` require 的加载机制? 32 | * ```[Question2]``` module.exports 与 exports 的区别 33 | * ```[Question3]``` 假设有 a.js、b.js 两个模块相互引用,会有什么问题?是否为陷入死循环? 34 | 35 | [阅读更多](/zh/module.md) 36 | 37 | ## [事件/异步](/zh/event-async.md) 38 | 39 | * ```[Question1]``` Node.js 中定时功能的顺序是怎样的? 40 | * ```[Question2]``` process.nextTick 与 setTimeout 递归调用区别? 41 | * ```[Question3]``` 解释下 JavaScript 中的 EventLoop(事件循环)? 42 | * ```[Question4]``` 解释下 NodeJS 中的 EventLoop(事件循环)? 43 | * ```[Question5]``` 什么是 Event Loop 和 Event Emitter ? 44 | 45 | [阅读更多](/zh/event-async.md) 46 | 47 | ## [进程/线程](/zh/process-threads.md) 48 | 49 | * ```[Question1]``` Node.js 什么是进程和线程?之间的区别? 50 | * ```[Question2]``` 什么是孤儿进程? 51 | * ```[Question3]``` 创建多进程时,代码里有 app.listen(port) 在进行 fork 时,为什么没有报端口被占用? 52 | * ```[Question4]``` 什么是 IPC 通信,如何建立 IPC 通信?什么场景下需要用到 IPC 通信? 53 | * ```[Question5]``` Node.js 是单线程还是多线程?进一步会提问为什么是单线程? 54 | * ```[Question6]``` 关于守护进程,是什么、为什么、怎么编写? 55 | * ```[Question7]``` 实现一个简单的命令行交互程序? 56 | * ```[Question8]``` 如何让一个 js 文件在 Linux 下成为一个可执行命令程序? 57 | * ```[Question9]``` 进程的当前工作目录是什么? 有什么作用? 58 | * ```[Question10]``` 多进程或多个 Web 服务之间的状态共享问题? 59 | 60 | [阅读更多](/zh/process-threads.md) 61 | 62 | ## [测试](/zh/test.md) 63 | 64 | * ```[Question1]``` 什么是测试金字塔? 请给一个例子! 65 | * ```[Question2]``` 什么是 Stub?用一个例子说明 66 | 67 | [阅读更多](/zh/test.md) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nodejs-Interview-Questions 2 | 3 | 这是一份包含 Node.js 学习与面试的问题列表,我会定期的更新本仓库,也欢迎您提交一些 PR 或者一些好的建议!希望能对您的学习与工作有所帮助,Good luck ❤️ 4 | 5 | 如果您想更全面的学习 Node.js 技术栈,为您推荐开源项目 [Nodejs-Roadmap](https://www.nodejs.red) 6 | 7 | * 语言: [:cn: 中文](/docs/zh/README.md) | [:uk: English](/docs/en/README.md) 8 | * 预览: [https://interview.nodejs.red](https://interview.nodejs.red) 9 | 10 | > 作者: 五月君,Node.js Developer,[慕课网认证作者](https://www.imooc.com/u/2667395)。 11 | 12 | ## [基础](/docs/zh/common.md) 13 | 14 | > 这个模块将会描述一些基础的或者通用的问题。 15 | 16 | * ```[Question1]``` 什么是 Node.js? 17 | * ```[Question2]``` 如何安装 Node.js? 18 | * ```[Question3]``` 如何用 Node.js 监听 80 端口? 19 | * ```[Question4]``` 什么是错误优先的回调函数? 20 | * ```[Question5]``` 你可以在 Node.js 中创建 Http 服务吗?通过代码来展示 21 | * ```[Question6]``` Node.js 的核心组件有哪些? 22 | * ```[Question7]``` 什么是“回调地狱”及如何避免它? 23 | * ```[Question8]``` 什么是 Node.js 的事件驱动编程? 24 | * ```[Question9]``` 什么是 NPM? 在 Node.js 中什么时候需要 NPM? 25 | * ```[Question10]``` Node.js 可以做什么? 10 个 Node.js 的应用场景? 26 | 27 | [阅读更多](/docs/zh/common.md) 28 | 29 | ## [模块](/zh/module.md) 30 | 31 | * ```[Question1]``` require 的加载机制? 32 | * ```[Question2]``` module.exports 与 exports 的区别 33 | * ```[Question3]``` 假设有 a.js、b.js 两个模块相互引用,会有什么问题?是否为陷入死循环? 34 | 35 | [阅读更多](/zh/module.md) 36 | 37 | ## [事件/异步](/docs/zh/event-async.md) 38 | 39 | * ```[Question1]``` Node.js 中定时功能的顺序是怎样的? 40 | * ```[Question2]``` process.nextTick 与 setTimeout 递归调用区别? 41 | * ```[Question3]``` 解释下 JavaScript 中的 EventLoop(事件循环)? 42 | * ```[Question4]``` 解释下 NodeJS 中的 EventLoop(事件循环)? 43 | * ```[Question5]``` 什么是 Event Loop 和 Event Emitter ? 44 | 45 | [阅读更多](/docs/zh/event-async.md) 46 | 47 | ## [进程/线程](/docs/zh/process-threads.md) 48 | 49 | * ```[Question1]``` Node.js 什么是进程和线程?之间的区别? 50 | * ```[Question2]``` 什么是孤儿进程? 51 | * ```[Question3]``` 创建多进程时,代码里有 app.listen(port) 在进行 fork 时,为什么没有报端口被占用? 52 | * ```[Question4]``` 什么是 IPC 通信,如何建立 IPC 通信?什么场景下需要用到 IPC 通信? 53 | * ```[Question5]``` Node.js 是单线程还是多线程?进一步会提问为什么是单线程? 54 | * ```[Question6]``` 关于守护进程,是什么、为什么、怎么编写? 55 | * ```[Question7]``` 实现一个简单的命令行交互程序? 56 | * ```[Question8]``` 如何让一个 js 文件在 Linux 下成为一个可执行命令程序? 57 | * ```[Question9]``` 进程的当前工作目录是什么? 有什么作用? 58 | * ```[Question10]``` 多进程或多个 Web 服务之间的状态共享问题? 59 | 60 | [阅读更多](/docs/zh/process-threads.md) 61 | 62 | ## [测试](/docs/zh/test.md) 63 | 64 | * ```[Question1]``` 什么是测试金字塔? 请给一个例子! 65 | * ```[Question2]``` 什么是 Stub?用一个例子说明 66 | 67 | [阅读更多](/docs/zh/test.md) -------------------------------------------------------------------------------- /docs/en/README.md: -------------------------------------------------------------------------------- 1 | # Nodejs-Interview-Questions 2 | 3 | This is a list of questions including Node.js learning and interviews. I will update this repository on a regular basis. You are also welcome to submit some PR or some good suggestions! I hope to help you with your study and work. Good luck ❤️ 4 | 5 | If you want to learn more about the **Node.js technology stack**, recommend the open source project [Nodejs-Roadmap](https://www.nodejs.red). But it is only available in Chinese, and you can translate it if you are interested. 6 | 7 | * Languages: [:cn: 中文](/zh/) | [:uk: English](/) 8 | * Preview: [https://interview.nodejs.red](https://interview.nodejs.red) 9 | 10 | ## [Common](/en/common.md) 11 | 12 | > Describe some basic or general issues here. 13 | 14 | * ```[Question1]``` What is Node.js? 15 | * ```[Question2]``` How can I install Node.js? 16 | * ```[Question3]``` How can you listen on port 80 with Node? 17 | * ```[Question4]``` What is an error-first callback? 18 | * ```[Question5]``` Can you create Http Server in Node.js, explain with code? 19 | * ```[Question6]``` What are the main components of Node.js? 20 | * ```[Question7]``` What is “callback hell” and how can it be avoided? 21 | * ```[Question8]``` What are the event-Driven Programming of Node.js? 22 | * ```[Question9]``` What is NPM? What is the need of NPM in Node.js? 23 | * ```[Question10]``` What does Node.js do? 10 application scenarios for Node.js? 24 | * ```[Question11]``` What is LTS releases of Node.js why should you care? 25 | 26 | [View more](/en/common.md) 27 | 28 | ## [Event/Async](/en/event-async.md) 29 | 30 | * ```[Question1]``` What are the timing features of Node.js? 31 | * ```[Question2]``` What is the difference between process.nextTick and setTimeout recursive calls? 32 | * ```[Question3]``` Explain event loop architecture of JavaScript. 33 | * ```[Question4]``` Explain event loop architecture of NodeJS. 34 | * ```[Question5]``` What is Event Loop and Event Emitter ? 35 | 36 | [View more](/en/event-async.md) 37 | 38 | ## [Process/Threads](/en/process-threads.md) 39 | 40 | * ```[Question1]``` What are processes and threads? difference between? 41 | * ```[Question2]``` What is an orphan process? 42 | * ```[Question3]``` creates multiple processes, there is ```app.listen(port)``` in the code. Why is it not reported that the port is occupied when forking? 43 | * ```[Question4]``` What is IPC communication, how to establish IPC communication? What scenarios need to use IPC communication? 44 | * ```[Question5]``` Node.js single-threaded or multi-threaded? Further questioning why is it single threaded? 45 | * ```[Question6]``` about the daemon, what, why, how to write? 46 | * ```[Question7]``` implements a simple command line interaction program? 47 | * ```[Question8]``` make a js file an executable command program under Linux? 48 | * ```[Question9]``` What is the current working directory of the process? What is the role? 49 | * ```[Question10]``` State sharing issues between multiple processes or multiple web services? 50 | 51 | [View more](/en/process-threads.md) 52 | 53 | ## [Test](/en/test.md) 54 | 55 | * ```[Question1]``` What's a test pyramid? Give an example! 56 | * ```[Question2]``` What's a stub? Name a use case. 57 | 58 | [View more](/en/test.md) -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |父子进程 IPC 通信交互图
207 | 208 | ## Q5:Node.js 是单线程还是多线程?进一步会提问为什么是单线程? 209 | 210 | 第一个问题,Node.js 是单线程还是多线程?这个问题是个基本的问题,在以往面试中偶尔提到还是有不知道的,Javascript 是单线程的,但是做为其在服务端运行环境的 Node.js 并非是单线程的。 211 | 212 | 第二个问题,Javascript 为什么是单线程?这个问题需要从浏览器说起,在浏览器环境中对于 DOM 的操作,试想如果多个线程来对同一个 DOM 操作是不是就乱了呢,那也就意味着对于DOM的操作只能是单线程,避免 DOM 渲染冲突。在浏览器环境中 UI 渲染线程和 JS 执行引擎是互斥的,一方在执行时都会导致另一方被挂起,这是由 JS 引擎所决定的。 213 | 214 | ## Q6:关于守护进程,是什么、为什么、怎么编写? 215 | 216 | 守护进程运行在后台不受终端的影响,什么意思呢?Node.js 开发的同学们可能熟悉,当我们打开终端执行 ```node app.js``` 开启一个服务进程之后,这个终端就会一直被占用,如果关掉终端,服务就会断掉,即前台运行模式。如果采用守护进程进程方式,这个终端我执行 ```node app.js``` 开启一个服务进程之后,我还可以在这个终端上做些别的事情,且不会相互影响。 217 | 218 | **创建步骤** 219 | 1. 创建子进程 220 | 2. 在子进程中创建新会话(调用系统函数 setsid) 221 | 3. 改变子进程工作目录(如:“/” 或 “/usr/ 等) 222 | 4. 父进程终止 223 | 224 | **Node.js 编写守护进程 Demo 展示** 225 | 226 | index.js 文件里的处理逻辑使用 spawn 创建子进程完成了上面的第一步操作。设置 options.detached 为 true 可以使子进程在父进程退出后继续运行(系统层会调用 setsid 方法),参考 [options_detached](http://nodejs.cn/api/child_process.html#child_process_options_detached),这是第二步操作。options.cwd 指定当前子进程工作目录若不做设置默认继承当前工作目录,这是第三步操作。运行 daemon.unref() 退出父进程,参考 [options.stdio](http://nodejs.cn/api/child_process.html#child_process_options_stdio),这是第四步操作。 227 | 228 | ```js 229 | // index.js 230 | const spawn = require('child_process').spawn; 231 | 232 | function startDaemon() { 233 | const daemon = spawn('node', ['daemon.js'], { 234 | cwd: '/usr', 235 | detached : true, 236 | stdio: 'ignore', 237 | }); 238 | 239 | console.log('守护进程开启 父进程 pid: %s, 守护进程 pid: %s', process.pid, daemon.pid); 240 | daemon.unref(); 241 | } 242 | 243 | startDaemon() 244 | ``` 245 | 246 | daemon.js 文件里处理逻辑开启一个定时器每 10 秒执行一次,使得这个资源不会退出,同时写入日志到子进程当前工作目录下 247 | 248 | ```js 249 | // /usr/daemon.js 250 | const fs = require('fs'); 251 | const { Console } = require('console'); 252 | 253 | // custom simple logger 254 | const logger = new Console(fs.createWriteStream('./stdout.log'), fs.createWriteStream('./stderr.log')); 255 | 256 | setInterval(function() { 257 | logger.log('daemon pid: ', process.pid, ', ppid: ', process.ppid); 258 | }, 1000 * 10); 259 | ``` 260 | 261 | [守护进程实现 Node.js 版本 源码地址](https://github.com/Q-Angelo/project-training/tree/master/nodejs/simple-daemon) 262 | 263 | **运行测试** 264 | 265 | ```bash 266 | $ node index.js 267 | 守护进程开启 父进程 pid: 47608, 守护进程 pid: 47609 268 | ``` 269 | 270 | 打开活动监视器查看,目前只有一个进程 47609,这就是我们需要进行守护的进程 271 | 272 |  273 | 274 | **守护进程阅读推荐** 275 | 276 | - [守护进程实现 (Node.js版本)](https://cnodejs.org/topic/57adfadf476898b472247eac) 277 | - [守护进程实现 (C语言版本)](https://github.com/ElemeFE/node-interview/blob/master/sections/zh-cn/process.md#%E5%AE%88%E6%8A%A4%E8%BF%9B%E7%A8%8B) 278 | 279 | **守护进程总结** 280 | 281 | 在实际工作中对于守护进程并不陌生,例如 PM2、Egg-Cluster 等,以上只是一个简单的 Demo 对守护进程做了一个说明,在实际工作中对守护进程的健壮性要求还是很高的,例如:进程的异常监听、工作进程管理调度、进程挂掉之后重启等等,这些还需要我们去不断思考。 282 | 283 | ## Q7:实现一个简单的命令行交互程序? 284 | 285 | 采用子进程 child_process 的 spawn 方法,如下所示: 286 | 287 | ```js 288 | const spawn = require('child_process').spawn; 289 | const child = spawn('echo', ["简单的命令行交互"]); 290 | child.stdout.pipe(process.stdout); // 将子进程的输出做为当前进程的输入,打印在控制台 291 | ``` 292 | 293 | ``` 294 | $ node execfile 295 | 简单的命令行交互 296 | ``` 297 | 298 | ## Q8:如何让一个 js 文件在 Linux 下成为一个可执行命令程序? 299 | 300 | 1. 新建 hello.js 文件,头部须加上 ```#!/usr/bin/env node```,表示当前脚本使用 Node.js 进行解析 301 | 2. 赋予文件可执行权限 chmod +x chmod +x /${dir}/hello.js,目录自定义 302 | 3. 在 /usr/local/bin 目录下创建一个软链文件 ```sudo ln -s /${dir}/hello.js /usr/local/bin/hello```,文件名就是我们在终端使用的名字 303 | 4. 终端执行 hello 相当于输入 node hello.js 304 | 305 | ```js 306 | #!/usr/bin/env node 307 | 308 | console.log('hello world!'); 309 | ``` 310 | 311 | 终端测试 312 | 313 | ```bash 314 | $ hello 315 | hello world! 316 | ``` 317 | 318 | ## Q9:进程的当前工作目录是什么? 有什么作用? 319 | 320 | 进程的当前工作目录可以通过 process.cwd() 命令获取,默认为当前启动的目录,如果是创建子进程则继承于父进程的目录,可通过 process.chdir() 命令重置,例如通过 spawn 命令创建的子进程可以指定 cwd 选项设置子进程的工作目录。 321 | 322 | 有什么作用?例如,通过 fs 读取文件,如果设置为相对路径则相对于当前进程启动的目录进行查找,所以,启动目录设置有误的情况下将无法得到正确的结果。还有一种情况程序里引用第三方模块也是根据当前进程启动的目录来进行查找的。 323 | 324 | ```js 325 | // 示例 326 | process.chdir('/Users/may/Documents/test/') // 设置当前进程目录 327 | 328 | console.log(process.cwd()); // 获取当前进程目录 329 | ``` 330 | 331 | ## Q10:多进程或多个 Web 服务之间的状态共享问题? 332 | 333 | 多进程模式下各个进程之间是相互独立的,例如用户登陆之后 session 的保存,如果保存在服务进程里,那么如果我有 4 个工作进程,每个进程都要保存一份这是没必要的,假设服务重启了数据也会丢失。多个 Web 服务也是一样的,还会出现我在 A 机器上创建了 Session,当负载均衡分发到 B 机器上之后还需要在创建一份。一般的做法是通过 Redis 或者 数据库来做数据共享。 334 | -------------------------------------------------------------------------------- /docs/en/process-threads.md: -------------------------------------------------------------------------------- 1 | # Process/Threads 2 | 3 | 通过对以下面试题的分享,助您更好的理解 Node.js 的进程和线程相关知识,关于进程和线程详细介绍,参考另一篇文章 [Node.js 线程和进程](https://www.nodejs.red/#/nodejs/process-threads) 4 | 5 | 6 | ## Q1: What are processes and threads? difference between? 7 | 8 | Threads and processes are a very basic concept of the server. After the concept of processes and threads is introduced in the article [Node.js Advanced Processes and Threads](https://www.imooc.com/article/288006) The actual application of the process and thread in Node.js is given. For this piece of advice that is not very understandable, look at it first. 9 | 10 | ## Q2: What is an orphan process? 11 | 12 | After the parent process creates the child process, the parent process exits, but one or more child processes corresponding to the parent process are still running. These child processes are adopted by the system's init process, and the corresponding process ppid is 1. This is the orphan process 13 | 14 | **For example** 15 | 16 | ```js 17 | // master.js 18 | const fork = require('child_process').fork; 19 | const server = require('net').createServer(); 20 | server.listen(3000); 21 | const worker = fork('worker.js'); 22 | 23 | worker.send('server', server); 24 | console.log('worker process created, pid: %s ppid: %s', worker.pid, process.pid); 25 | process.exit(0); 26 | ``` 27 | 28 | ```js 29 | // worker.js 30 | const http = require('http'); 31 | const server = http.createServer((req, res) => { 32 | res.end('I am worker, pid: ' + process.pid + ', ppid: ' + process.ppid); 33 | }); 34 | 35 | let worker; 36 | process.on('message', function (message, sendHandle) { 37 | if (message === 'server') { 38 | worker = sendHandle; 39 | worker.on('connection', function(socket) { 40 | server.emit('connection', socket); 41 | }); 42 | } 43 | }); 44 | ``` 45 | 46 | The console tests to output the current worker process pid and the parent process ppid: 47 | 48 | ```bash 49 | $ node master 50 | worker process created, pid: 32971 ppid: 32970 51 | ``` 52 | 53 | Since the parent process is exited in master.js, the activity monitor shows only the worker process. 54 | 55 |  56 | 57 | Verify again, open the console call interface, you can see that the ppid corresponding to the work process 32971 is 1 (for the init process), which has become an orphan process. 58 | 59 | ```bash 60 | $ curl http://127.0.0.1:3000 61 | I am worker, pid: 32971, ppid: 1 62 | ``` 63 | 64 | [Source code](https://github.com/Q-Angelo/project-training/tree/master/nodejs/orphan-process) 65 | 66 | ## Q3:creates multiple processes, there is ```app.listen(port)``` in the code. Why is it not reported that the port is occupied when forking? 67 | 68 | 先看下端口被占用的情况 69 | 70 | ```js 71 | // master.js 72 | const fork = require('child_process').fork; 73 | const cpus = require('os').cpus(); 74 | 75 | for (let i=0; i父子进程 IPC 通信交互图
209 | 210 | ## Q5:Node.js single-threaded or multi-threaded? Further questioning why is it single threaded? 211 | 212 | 第一个问题,Node.js 是单线程还是多线程?这个问题是个基本的问题,在以往面试中偶尔提到还是有不知道的,Javascript 是单线程的,但是做为其在服务端运行环境的 Node.js 并非是单线程的。 213 | 214 | 第二个问题,Javascript 为什么是单线程?这个问题需要从浏览器说起,在浏览器环境中对于 DOM 的操作,试想如果多个线程来对同一个 DOM 操作是不是就乱了呢,那也就意味着对于DOM的操作只能是单线程,避免 DOM 渲染冲突。在浏览器环境中 UI 渲染线程和 JS 执行引擎是互斥的,一方在执行时都会导致另一方被挂起,这是由 JS 引擎所决定的。 215 | 216 | ## Q6:about the daemon, what, why, how to write? 217 | 218 | 守护进程运行在后台不受终端的影响,什么意思呢?Node.js 开发的同学们可能熟悉,当我们打开终端执行 ```node app.js``` 开启一个服务进程之后,这个终端就会一直被占用,如果关掉终端,服务就会断掉,即前台运行模式。如果采用守护进程进程方式,这个终端我执行 ```node app.js``` 开启一个服务进程之后,我还可以在这个终端上做些别的事情,且不会相互影响。 219 | 220 | **创建步骤** 221 | 1. 创建子进程 222 | 2. 在子进程中创建新会话(调用系统函数 setsid) 223 | 3. 改变子进程工作目录(如:“/” 或 “/usr/ 等) 224 | 4. 父进程终止 225 | 226 | **Node.js 编写守护进程 Demo 展示** 227 | 228 | index.js 文件里的处理逻辑使用 spawn 创建子进程完成了上面的第一步操作。设置 options.detached 为 true 可以使子进程在父进程退出后继续运行(系统层会调用 setsid 方法),参考 [options_detached](http://nodejs.cn/api/child_process.html#child_process_options_detached),这是第二步操作。options.cwd 指定当前子进程工作目录若不做设置默认继承当前工作目录,这是第三步操作。运行 daemon.unref() 退出父进程,参考 [options.stdio](http://nodejs.cn/api/child_process.html#child_process_options_stdio),这是第四步操作。 229 | 230 | ```js 231 | // index.js 232 | const spawn = require('child_process').spawn; 233 | 234 | function startDaemon() { 235 | const daemon = spawn('node', ['daemon.js'], { 236 | cwd: '/usr', 237 | detached : true, 238 | stdio: 'ignore', 239 | }); 240 | 241 | console.log('守护进程开启 父进程 pid: %s, 守护进程 pid: %s', process.pid, daemon.pid); 242 | daemon.unref(); 243 | } 244 | 245 | startDaemon() 246 | ``` 247 | 248 | daemon.js 文件里处理逻辑开启一个定时器每 10 秒执行一次,使得这个资源不会退出,同时写入日志到子进程当前工作目录下 249 | 250 | ```js 251 | // /usr/daemon.js 252 | const fs = require('fs'); 253 | const { Console } = require('console'); 254 | 255 | // custom simple logger 256 | const logger = new Console(fs.createWriteStream('./stdout.log'), fs.createWriteStream('./stderr.log')); 257 | 258 | setInterval(function() { 259 | logger.log('daemon pid: ', process.pid, ', ppid: ', process.ppid); 260 | }, 1000 * 10); 261 | ``` 262 | 263 | [守护进程实现 Node.js 版本 源码地址](https://github.com/Q-Angelo/project-training/tree/master/nodejs/simple-daemon) 264 | 265 | **运行测试** 266 | 267 | ```bash 268 | $ node index.js 269 | 守护进程开启 父进程 pid: 47608, 守护进程 pid: 47609 270 | ``` 271 | 272 | 打开活动监视器查看,目前只有一个进程 47609,这就是我们需要进行守护的进程 273 | 274 |  275 | 276 | **守护进程阅读推荐** 277 | 278 | - [守护进程实现 (Node.js版本)](https://cnodejs.org/topic/57adfadf476898b472247eac) 279 | - [守护进程实现 (C语言版本)](https://github.com/ElemeFE/node-interview/blob/master/sections/zh-cn/process.md#%E5%AE%88%E6%8A%A4%E8%BF%9B%E7%A8%8B) 280 | 281 | **守护进程总结** 282 | 283 | 在实际工作中对于守护进程并不陌生,例如 PM2、Egg-Cluster 等,以上只是一个简单的 Demo 对守护进程做了一个说明,在实际工作中对守护进程的健壮性要求还是很高的,例如:进程的异常监听、工作进程管理调度、进程挂掉之后重启等等,这些还需要我们去不断思考。 284 | 285 | ## Q7:implements a simple command line interaction program? 286 | 287 | 采用子进程 child_process 的 spawn 方法,如下所示: 288 | 289 | ```js 290 | const spawn = require('child_process').spawn; 291 | const child = spawn('echo', ["简单的命令行交互"]); 292 | child.stdout.pipe(process.stdout); // 将子进程的输出做为当前进程的输入,打印在控制台 293 | ``` 294 | 295 | ``` 296 | $ node execfile 297 | 简单的命令行交互 298 | ``` 299 | 300 | ## Q8:make a js file an executable command program under Linux? 301 | 302 | 1. 新建 hello.js 文件,头部须加上 ```#!/usr/bin/env node```,表示当前脚本使用 Node.js 进行解析 303 | 2. 赋予文件可执行权限 chmod +x chmod +x /${dir}/hello.js,目录自定义 304 | 3. 在 /usr/local/bin 目录下创建一个软链文件 ```sudo ln -s /${dir}/hello.js /usr/local/bin/hello```,文件名就是我们在终端使用的名字 305 | 4. 终端执行 hello 相当于输入 node hello.js 306 | 307 | ```js 308 | #!/usr/bin/env node 309 | 310 | console.log('hello world!'); 311 | ``` 312 | 313 | 终端测试 314 | 315 | ```bash 316 | $ hello 317 | hello world! 318 | ``` 319 | 320 | ## Q9:What is the current working directory of the process? What is the role? 321 | 322 | 进程的当前工作目录可以通过 process.cwd() 命令获取,默认为当前启动的目录,如果是创建子进程则继承于父进程的目录,可通过 process.chdir() 命令重置,例如通过 spawn 命令创建的子进程可以指定 cwd 选项设置子进程的工作目录。 323 | 324 | 有什么作用?例如,通过 fs 读取文件,如果设置为相对路径则相对于当前进程启动的目录进行查找,所以,启动目录设置有误的情况下将无法得到正确的结果。还有一种情况程序里引用第三方模块也是根据当前进程启动的目录来进行查找的。 325 | 326 | ```js 327 | // 示例 328 | process.chdir('/Users/may/Documents/test/') // 设置当前进程目录 329 | 330 | console.log(process.cwd()); // 获取当前进程目录 331 | ``` 332 | 333 | ## Q10:State sharing issues between multiple processes or multiple web services? 334 | 335 | 多进程模式下各个进程之间是相互独立的,例如用户登陆之后 session 的保存,如果保存在服务进程里,那么如果我有 4 个工作进程,每个进程都要保存一份这是没必要的,假设服务重启了数据也会丢失。多个 Web 服务也是一样的,还会出现我在 A 机器上创建了 Session,当负载均衡分发到 B 机器上之后还需要在创建一份。一般的做法是通过 Redis 或者 数据库来做数据共享。 336 | -------------------------------------------------------------------------------- /docs/en/common.md: -------------------------------------------------------------------------------- 1 | 2 | # Common 3 | 4 | ## Q1: What is Node.js? 5 | 6 | Node.js is a server side JavaScript platform which is built on Google Chrome’s JavaScript V8 engine. It is an open source and cross platform application to develop server side and networking application. Anyone can develop the Node.js application by written code in JavaScript and it can be run on Microsoft Windows, Linux or OS X. 7 | 8 | Node.js is not a new language and also it is not just framework built on JavaScript. It is built on Chrome's JavaScript Runtime, so the code is written, execute very similarly to browser. 9 | 10 | **Features of Node.js** 11 | 12 | Following are some important feature of Node.js 13 | 14 | - **Fast in Code execution**: It is very fast in code execution. 15 | 16 | - **Highly scalable**: Node.js uses single thread model for event looping. Events are responded to the server without blocking other operation. This makes the Node.js highly scalable. Traditional servers Create limited threads to handle request and Node.js Creates single thread that provide service to much larger number of requests. 17 | 18 | - **Event Driven and Asynchronous**: All API of Node.js is asynchronous. It means that server is moving the next API call without wait for returning data of previous request. 19 | 20 | - **No Buffering**: Node.js is never buffering any data. 21 | 22 | Many of us are confused about Node.js. It is not a web server like Apache. Node.js is providing new way to execute our code. It is JavaScript runtime. Node.js is provides facility to create HTTP server and we can host our application on same. 23 | 24 | Source: [Introduction To Node.js](https://www.c-sharpcorner.com/article/introduction-to-node-js/) 25 | 26 | ## Q2: How can I install Node.js? 27 | 28 | We can download Node.js software from the website [https://nodejs.org/en/](https://nodejs.org/en/). 29 | 30 | **nvm install** 31 | 32 | It is recommended that you use the nvm tool to install, which is convenient for later upgrade management. Here are the installation steps: 33 | 34 | * nvm installation:wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash 35 | * view all Node.js versions:nvm ls-remote 36 | * view local Node.js versions:nvm ls 37 | * Node.js installation:nvm install v6.9.5 38 | * set the system default Node.js version:nvm alias default v6.9.5 39 | 40 | **Verifying Node.js Installation** 41 | 42 | After successful installation of Node.js, you can check it’s working. 43 | 44 | Open Command Prompt and write the following command: 45 | 46 | ```node 47 | $ node 48 | ``` 49 | 50 | Next, at the Node.js prompt will appear. After the prompt is visible, write the following command: 51 | 52 | console.log(“NeErAj KuMaR”); 53 | 54 | Press Enter 55 | 56 |  57 | 58 | ## Q3: How can you listen on port 80 with Node? 59 | 60 | Trick question! You should not try to listen with Node on port 80 (in Unix-like systems) - to do so you would need superuser rights, but it is not a good idea to run your application with it. 61 | 62 | Still, if you want to have your Node.js application listen on port 80, here is what you can do. Run the application on any port above 1024, then put a reverse proxy like nginx in front of it. 63 | 64 | ## Q4: What is an error-first callback? 65 | 66 | Error-first callbacks are used to pass errors and data as well. You have to pass the error as the first parameter, and it has to be checked to see if something went wrong. Additional arguments are used to pass data. 67 | 68 | ```js 69 | fs.readFile(filePath, function(err, data) { 70 | if (err) { 71 | // handle the error 72 | return console.log(err) 73 | } 74 | 75 | // return the data object 76 | return data; 77 | }) 78 | ``` 79 | 80 | ## Q5: Can you create Http Server in Node.js, explain with code? 81 | 82 | Yes, creating an Http Server in Node.js is very simple, we can do it through the HTTP module. 83 | 84 | ```js 85 | const http = require('http'); 86 | const server = http.createServer((request, response) => { 87 | if (request.url === '/hello') { 88 | response.writeHead(200, { 89 | 'Content-Type': 'text/plain', 90 | }); 91 | response.end('hello world!'); 92 | } else { 93 | response.end('OK!'); 94 | } 95 | }); 96 | 97 | server.listen(3000, '127.0.0.1', () => { 98 | console.log('service is listening at http://127.0.0.1:3000'); 99 | }); 100 | ``` 101 | 102 | ## Q6: What are the main components of Node.js? 103 | 104 | The main components of NodeJs are APIs, a V8 Engine and Libuv. 105 | 106 | **Libuv Library** 107 | 108 | Libuv is a multi-platform support library for asynchronous I/O. It was developed for Node.js using C and C++. But it's also used by Mozilla's Rust language, Luvit, Julia, pyuv and others. 109 | 110 | This libuv library is the main part for I/O related operations like reading files and interacting with the OS. 111 | 112 | You can check it out on GitHub for more information about [the libuv library](https://github.com/nikhilm/uvbook). 113 | 114 | **V8 Engine** 115 | 116 | From Google: “V8 is Google's open-source high-performance JavaScript engine, written in C++ and used in Google Chrome, the open source browser from Google. It implements ECMAScript as specified in ECMA-262, 3rd edition and runs on Windows XP and Vista, Mac OS X 10.5+, and Linux systems that use IA-32, ARM or MIPS processors. V8 can run standalone, or can be embedded into any C++ application”. 117 | 118 | If you are interested in learning more about the V8 engine, please visit [here](https://v8.dev/). 119 | 120 | **APIs (NodeJS Core Libs)** 121 | 122 | The NodeJs APIs are nothing but functions to do something upon your request. By default the NodeJS apis are asynchronous in nature but still you can use NodeJS APIs synchronously. 123 | 124 | For example, the fs module could be used either synchronously or asynchronously. 125 | 126 | ```js 127 | var fs = require('fs'); 128 | fs.readFile('/files/help.txt', function(err, buf) { 129 | // use fs.readFileSync() for sync operation. console.log(buf.toString()); 130 | }); 131 | ``` 132 | 133 | Source: [Introduction to NodeJS, A SSJS: Part I - Components Explained](https://www.c-sharpcorner.com/UploadFile/dbd951/introduction-to-nodejs-a-ssjs-part-i/) 134 | 135 | ## Q7: What is “callback hell” and how can it be avoided? 136 | 137 | “Callback hell” refers to heavily nested callbacks that have become unweildy or unreadable. 138 | 139 | An example of heavily nested code is below: 140 | 141 | ```js 142 | query("SELECT clientId FROM clients WHERE clientName='picanteverde';", function(id){ 143 | query(`SELECT * FROM transactions WHERE clientId=${id}`, function(transactions){ 144 | transactions.each((transac) => { 145 | query(`UPDATE transactions SET value = ${transac.value*0.1} WHERE id=${transac.id}`, (error) => { 146 | if(!error){ 147 | console.log("success!!"); 148 | }else{ 149 | console.log("error"); 150 | } 151 | }); 152 | }); 153 | }); 154 | }); 155 | ``` 156 | 157 | At one point, the primary method to fix callback hell was modularization. The callbacks are broken out into independent functions which can be called with some parameters. So the first level of improvement might be: 158 | 159 | ```js 160 | const logError = (error) => { 161 | if(!error){ 162 | console.log("success!!"); 163 | }else{ 164 | console.log("error"); 165 | } 166 | }, 167 | updateTransaction = (t) => { 168 | query(`UPDATE transactions SET value = ${t.value*0.1} WHERE id=${t.id}`, logError); 169 | }, 170 | handleTransactions = (transactions) => { 171 | transactions.each(updateTransaction); 172 | }, 173 | handleClient = (id) => { 174 | query(`SELECT * FROM transactions WHERE clientId=${id}`, handleTransactions); 175 | }; 176 | 177 | query("SELECT clientId FROM clients WHERE clientName='picanteverde';",handleClient); 178 | ``` 179 | 180 | Even though this code is much easier to read, and we created some functions that we can even reuse later, in some cases it may be appropriate to use a more robust solution in the form of promises. Promises allow additional desirable behavior such as error propagation and chaining. Node.js includes native support for them. 181 | 182 | Additionally, a more supercharged solution to callback hell was provided by generators, as these can resolve execution dependency between different callbacks. However, generators are much more advanced and it might be overkill to use them for this purpose. To read more about generators you can start with [this post]((http://strongloop.com/strongblog/how-to-generators-node-js-yield-use-cases/)). 183 | 184 | However, these approaches are pretty dated at this point. The current solution is to use async/await—an approach that leverages Promises and finally makes it easy to flatten the so-called “pyramid of doom” shown above. 185 | 186 | Source: [8 Essential Node.js Interview Questions](https://www.toptal.com/nodejs/interview-questions) 187 | 188 | ## Q8: What are the event-Driven Programming of Node.js? 189 | 190 | Event-Driven Programming is the term where the flow of the code is determined by events (click, load and so on). It's one of the basic milestones of today's popular programming languages, such as C#, Java and many more; I won't dwell on all of them here. In Node.js and moreover in any kind of JavaScript project, you'll be using or have used event-driven processes. Whether it's a page onload or a button click event, this is something you have done, whether you knew it or not. 191 | 192 | Let's make an example to the classic event-driven process and how its done in NodeJS: 193 | 194 | result = getJSONfromDestination(); 195 | binddata(result); 196 | The operation above requires a blocking I/O process (single-threaded operation that waits for the previously working synchronous code). 197 | 198 | Now let's have a look at how we do the asynchronous way (a non-blocking I/O process). 199 | 200 | json_finished = function(result){ 201 | binddata(result); 202 | } 203 | 204 | getJSONfromDestination(jsonfinished); 205 | As you can see, this is a non-blocking sample, because json_finished does not work first as you can imagine. 206 | It starts working when you call the getJSONfromDestination method and send param as the function to json_finished. 207 | 208 | Source: [NodeJS Series #6: Event - Driven Programming](https://www.c-sharpcorner.com/UploadFile/iersoy/nodejs-series-sharp6-event-driven-programming/) 209 | 210 | ## Q9: What is NPM? What is the need of NPM in Node.js? 211 | 212 | NPM stands for Node.js Package Management. It comes with Node.js platform and allows us to install various packages for Node.js. This package manages and supports various commands to install and remove the modules. Here one important note is we require either package.json file or the node_modules folder to install modules locally. 213 | 214 | One of the best things about npm is that it locally stores all dependencies. For example, if module X uses module A version 1.0, and module Y uses module A version 1.5, then both X and Y will have their own local copies of module A. 215 | 216 | ```js 217 | // Module X 218 | { 219 | "name": "X", 220 | "dependencies": { 221 | "A": "^1.0" 222 | } 223 | } 224 | ``` 225 | 226 | ```js 227 | // Module Y 228 | { 229 | "name": "Y", 230 | "dependencies": { 231 | "A": "^1.5" 232 | } 233 | } 234 | ``` 235 | 236 | **Need of npm package** 237 | 238 | When we are developing some Node.js projects, we may encounter some places that need NPM, such as linking Redis, MongoDB, or sending a request Request. These modules can make us more focused on business development, of course, sometimes you will have something special. The need, at this time, may need to encapsulate an NPM module to achieve reuse. 239 | 240 | Source: [How to Create Nodejs Module and Publish Over to Npm](https://www.c-sharpcorner.com/UploadFile/g_arora/how-to-create-nodejs-module-and-publish-over-to-npm/) 241 | 242 | ## Q10: What does Node.js do? 10 application scenarios for Node.js? 243 | 244 | Web Server Backend (Java, PHP do node. JS can Do)、Command-line tools,Now count the 10 scenarios of Node.js: 245 | 246 | 1. Web Development: Express + EJS + MongoDB(mongoose)/Mysql 247 | 2. REST Development: Restify 248 | 3. Web chat Room (IM): Express + Socket.io 249 | 4. Web Crawler: Cheerio/request 250 | 5. Web Blog: Hexo 251 | 6. Web Forum: Nodeclub 252 | 7. Web Slideshow: Cleaver 253 | 8. Front-end package management platform: bower.js 254 | 9. OAuth Certification: Passport 255 | 10. Timer Task Tool: Later 256 | 257 | Source: [What does node. js do? 10 application scenarios for node. js](https://topic.alibabacloud.com/a/what-does-node-js-do-10-application-scenarios-for-node-js_4_87_30002440.html) 258 | 259 | 260 | ## Q11: What is LTS releases of Node.js why should you care? 261 | 262 | An LTS(Long Term Support) version of Node.js receives all the critical bug fixes, security updates and performance improvements. 263 | 264 | LTS versions of Node.js are supported for at least 18 months and are indicated by even version numbers (e.g. 4, 6, 8). They’re best for production since the LTS release line is focussed on stability and security, whereas the Current release line has a shorter lifespan and more frequent updates to the code. Changes to LTS versions are limited to bug fixes for stability, security updates, possible npm updates, documentation updates and certain performance improvements that can be demonstrated to not break existing applications. 265 | 266 | Source: [github.com/i0natan/nodebestpractices](github.com/i0natan/nodebestpractices) --------------------------------------------------------------------------------