This article will share with you some front-end interview questions about Node. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "nodejs Tutorial"
**1 . Why use node? **
Features: Simple and powerful, lightweight and scalable. The simplicity is reflected in node
using javascript, json
for encoding, everyone can do it;
The power is reflected in non-blocking IO, which can adapt to block transmission of data, which is slower Network environment, especially good at high concurrent access; lightweight is reflected in node
itself is both a code and a server, and the front and back ends use a unified language; scalable is reflected in that it can easily cope with multiple instances and multi-server architectures, while having Massive third-party application components
2. What does the node architecture look like?
It is mainly divided into three layers, applicationapp >> V8 And node built-in architecture>> Operating system.
V8 is the environment in which node runs, and can be understood as a node virtual machine. The built-in architecture of node can be divided into three layers: core module (javascript
implementation) >> c
binding>> libuv CAes http
.
3. What core modules does node have?
EventEmitter, Stream, FS, Net和全局对象
4. What global objects does node have?
process, console, Buffer和exports
5. What are the common methods of process?
process.stdin, process.stdout, process.stderr, process.on, process.env, process.argv, process.arch, process.platform, process.exit
6. What are the common methods of console?
console.log/console.info, console.error/console.warning, console.time/console.timeEnd, console.trace, console.table
7. What are the timing functions of node?
setTimeout/clearTimeout, setInterval/clearInterval, setImmediate/clearImmediate, process.nextTick
8. What does the event loop in node look like?
The overall execution sequence is: process.nextTick >> setImmidate >> setTimeout/SetInterval
Link
9. How to apply Buffer in node?
Buffer
Yes Used to process binary data, such as pictures, mp3, database files, etc. Buffer
supports various encoding and decoding, and binary string conversion.
**10. What is EventEmitter? **
EventEmitter
is one of node
that implements the observer pattern Class, the main function is to listen and transmit messages, used to deal with multi-module interaction issues.
11. How to implement an EventEmitter?
It is mainly divided into three steps: define an Subclass, call the constructor, inheritEventEmitter
Code demonstration
var util = require(‘util’); var EventEmitter = require(‘events’).EventEmitter; function MyEmitter() { EventEmitter.call(this); } // 构造函数 util.inherits(MyEmitter, EventEmitter); // 继承 var em = new MyEmitter(); em.on('hello', function(data) { console.log('收到事件hello的数据:', data); }); // 接收事件,并打印到控制台 em.emit('hello', 'EventEmitter传递消息真方便!');
12. What are the typical applications of EventEmitter?
1) Passing messages between modules
2) Passing messages inside and outside the callback function
3) Processing stream data, because the stream is implemented based on EventEmitter.
4) Related applications of the observer mode emission triggering mechanism
13. How to capture the error event of EventEmitter?
Just listen to the error
event. If there are multiple EventEmitter
, you can also use domain
to handle error events uniformly.
Code Demonstration
var domain = require('domain'); var myDomain = domain.create(); myDomain.on('error', function(err){ console.log('domain接收到的错误事件:', err); }); // 接收事件并打印 myDomain.run(function(){ var emitter1 = new MyEmitter(); emitter1.emit('error', '错误事件来自emitter1'); emitter2 = new MyEmitter(); emitter2.emit('error', '错误事件来自emitter2'); });
14, EventEmitter What is the use of the newListenser event? newListener
can be used for reflection of the event mechanism, special applications, event management, etc. When any on event is added to EventEmitter
, the newListener
event will be triggered. Based on this mode, we can do a lot of custom processing.
Code Demonstration
var emitter3 = new MyEmitter(); emitter3.on('newListener', function(name, listener) { console.log("新事件的名字:", name); console.log("新事件的代码:", listener); setTimeout(function(){ console.log("我是自定义延时处理机制"); }, 1000); }); emitter3.on('hello', function(){ console.log('hello node'); });
**15. What is Stream? **
stream
is a data management model based on eventEventEmitter
. It is composed of various abstract interfaces, mainly including writable, readable, read-write, convertible and other types.
16. What are the benefits of Stream?
Non-blocking data processing improves efficiency, fragment processing saves memory, pipeline processing is convenient and scalable, etc.
17. What are the typical applications of Stream?
File, network, data conversion, audio and video, etc.
18. How to capture the error event of Stream?
Listen to error
events, the method is the same as EventEmitter
##**19. What are the commonly used Streams and when should they be used? **
Readable is a readable stream and is used as an input data source;
Writable is a writable stream and is used as an output source Use;
Duplex is a read-write stream. It serves as an output source to accept being written, and at the same time serves as an input source to be read by subsequent streams.
TransformThe mechanism is the same as
Duplex, both are bidirectional streams. The difference is that
Transfrom only needs to implement one function
_transfrom(chunk, encoding, callback);And
Duplex needs to implement the
_read(size) function and the
_write(chunk, encoding, callback) function respectively.
**20. Implement a Writable Stream? **
Three steps: 1) Constructorcall Writable
Insert code snippet here 3) Implement
_write(chunk, encoding, callback)function
代码演示
var Writable = require('stream').Writable; var util = require('util'); function MyWritable(options) { Writable.call(this, options); } // 构造函数 util.inherits(MyWritable, Writable); // 继承自Writable MyWritable.prototype._write = function(chunk, encoding, callback) { console.log("被写入的数据是:", chunk.toString()); // 此处可对写入的数据进行处理 callback(); }; process.stdin.pipe(new MyWritable()); // stdin作为输入源,MyWritable作为输出源
21、内置的fs模块架构是什么样子的?
fs
模块主要由下面几部分组成:
1) POSIX
文件Wrapper
,对应于操作系统的原生文件操作
2) 文件流 fs.createReadStream
和fs.createWriteStream
3) 同步文件读写,fs.readFileSync
和fs.writeFileSync
4) 异步文件读写, fs.readFile
和fs.writeFile
**22、读写一个文件有多少种方法? **
1) POSIX式低层读写
2) 流式读写
3) 同步文件读写
4) 异步文件读写
23、怎么读取json配置文件?
第一种是利用node
内置的require('data.json')
机制,直接得到js对象;
第二种是读入文件入内容,然后用JSON.parse(content)
转换成js
对象.二者的区别是require
机制情况下,如果多个模块都加载了同一个json
文件,那么其中一个改变了js
对象,其它跟着改变,这是由node
模块的缓存机制造成的,只有一个js
模块对象; 第二种方式则可以随意改变加载后的js
变量,而且各模块互不影响,因为他们都是独立的,是多个js
对象.
24、fs.watch和fs.watchFile有什么区别,怎么应用?
fs.watch
利用操作系统原生机制来监听,可能不适用网络文件系统; fs.watchFile
则是定期检查文件状态变更,适用于网络文件系统,但是相比fs.watch
有些慢,因为不是实时机制.
25、node的网络模块架构是什么样子的?
node
全面支持各种网络服务器和客户端,包括tcp, http/https, tcp, udp, dns, tls/ssl
等.
26、node是怎样支持https,tls的?
1) openssl
生成公钥私钥
2) 服务器或客户端使用https
替代http
3) 服务器或客户端加载公钥私钥证书
27、实现一个简单的http服务器?
思路是加载http模块,创建服务器,监听端口.
代码演示
var http = require('http'); // 加载http模块 http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); // 200代表状态成功, 文档类型是给浏览器识别用的 res.write('<meta charset="UTF-8"><h1>我是标题啊!</h1><font color="red">这么原生,初级的服务器,下辈子能用着吗?!</font>'); // 返回给客户端的html数据 res.end(); // 结束输出流 }).listen(3000); // 绑定3ooo, 查看效果请访问 http://localhost:3000
**28、为什么需要child-process? **
node
是异步非阻塞的,这对高并发非常有效.可是我们还有其它一些常用需求,比如和操作系统shell
命令交互,调用可执行文件,创建子进程进行阻塞式访问或高CPU计算等,child-process
就是为满足这些需求而生的.child-process
顾名思义,就是把node
阻塞的工作交给子进程去做.
29、exec,execFile,spawn和fork都是做什么用的?
exec
可以用操作系统原生的方式执行各种命令,如管道 cat ab.txt | grep hello;execFile
是执行一个文件;spawn
是流式和操作系统进行交互;fork
是两个node
程序(javascript
)之间时行交互.
30、实现一个简单的命令行交互程序?
spawn
代码演示
var cp = require('child_process'); var child = cp.spawn('echo', ['你好', "钩子"]); // 执行命令 child.stdout.pipe(process.stdout); // child.stdout是输入流,process.stdout是输出流 // 这句的意思是将子进程的输出作为当前程序的输入流,然后重定向到当前程序的标准输出,即控制台
**31、两个node程序之间怎样交互? **
用fork嘛,上面讲过了.原理是子程序用process.on, process.send
,父程序里用child.on,child.send
进行交互.
代码演示
1) fork-parent.js var cp = require('child_process'); var child = cp.fork('./fork-child.js'); child.on('message', function(msg){ console.log('老爸从儿子接受到数据:', msg); }); child.send('我是你爸爸,送关怀来了!'); 2) fork-child.js process.on('message', function(msg){ console.log("儿子从老爸接收到的数据:", msg); process.send("我不要关怀,我要银民币!"); });
**32、怎样让一个js文件变得像linux命令一样可执行? **
1) 在myCommand.js
文件头部加入#!/usr/bin/env node
2) chmod
命令把js文件改为可执行即可
3) 进入文件目录,命令行输入myComand
就是相当于node myComand.js
了
33、child-process和process的stdin,stdout,stderror是一样的吗?
概念都是一样的,输入,输出,错误,都是流.区别是在父程序眼里,子程序的stdout
是输入流,stdin
是输出流
34、node中的异步和同步怎么理解
node是单线程的,异步是通过一次次的循环事件队列来实现的.同步则是说阻塞式的IO,这在高并发环境会是一个很大的性能问题,所以同步一般只在基础框架的启动时使用,用来加载配置文件,初始化程序什么的
**35、有哪些方法可以进行异步流程的控制? **
1) 多层嵌套回调
2) 为每一个回调写单独的函数,函数里边再回调
3) 用第三方框架比方async, q, promise
等
36、怎样绑定node程序到80端口?
1) sudo
2) apache/nginx
代理
3) 用操作系统的firewall iptables
进行端口重定向
37、有哪些方法可以让node程序遇到错误后自动重启?
1) runit
2) forever
3) nohup npm start &
38、怎样充分利用多个CPU?
一个CPU运行一个node实例
39、怎样调节node执行单元的内存大小?
用--max-old-space-size
和 --max-new-space-size
来设置 v8 使用内存的上限
**40、程序总是崩溃,怎样找出问题在哪里? **
1) node --prof
查看哪些函数调用次数多
2) memwatch
和heapdump
获得内存快照进行对比,查找内存溢出
**41、有哪些常用方法可以防止程序崩溃? **
1) try-catch-finally
2) EventEmitter/Stream error
事件处理
3) domain
统一控制
4) jshint
静态检查
5) jasmine/mocha
进行单元测试
42、怎样调试node程序?
node --debug app.js
和node-inspector
43、async都有哪些常用方法,分别是怎么用?
async
是一个js
类库,它的目的是解决js
中异常流程难以控制的问题.async
不仅适用在node.js
里,浏览器中也可以使用.
1) async.parallel
并行执行完多个函数后,调用结束函数
async.parallel([ function(){ ... }, function(){ ... } ], callback);
async.series
串行执行完多个函数后,调用结束函数async.series([ function(){ ... }, function(){ ... } ]);
async.waterfall
依次执行多个函数,后一个函数以前面函数的结果作为输入参数async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' });
async.map
异步执行多个数组,返回结果数组async.map(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file });
async.filter
异步过滤多个数组,返回结果数组async.filter(['file1','file2','file3'], fs.exists, function(results){ // results now equals an array of the existing files });
44、express项目的目录大致是什么样子的
app.js, package.json, bin/www, public, routes, views.
45、express常用函数express.Router
路由组件,app.get
路由定向,app.configure
配置,app.set
设定参数,app.use
使用中间件
46、express中如何获取路由的参数/users/:name
使用req.params.name
来获取;req.body.username
则是获得表单传入参数username
;express
路由支持常用通配符 ?, +, *, and ()
47、express response有哪些常用方法res.download()
弹出文件下载res.end()
结束responseres.json()
返回json 在这里插入代码片
res.jsonp()
返回jsonpres.redirect()
重定向请求res.render()
渲染模板res.send()
返回多种形式数据res.sendFile
返回文件res.sendStatus()
返回状态
48、mongodb有哪些常用优化措施
类似传统数据库,索引和分区
49、mongoose是什么?有支持哪些特性?mongoose
是mongodb
的文档映射模型.主要由Schema
, Model
和Instance
三个方面组成.Schema
就是定义数据类型,Model
就是把Schema
和js
类绑定到一起,Instance
就是一个对象实例.
常见mongoose
操作有,save, update, find. findOne, findById, static
方法等
50、redis支持哪些功能
set/get, mset/hset/hmset/hmget/hgetall/hkeys, sadd/smembers, publish/subscribe, expire
51、redis最简单的应用
var redis = require("redis"), client = redis.createClient(); client.set("foo_rand000000000000", "some fantastic value"); client.get("foo_rand000000000000", function (err, reply) { console.log(reply.toString()); }); client.end();
52、apache,nginx有什么区别?
二者都是代理服务器,功能类似.apache
应用简单,相当广泛.nginx
在分布式,静态转发方面比较有优势
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of Share some front-end interview questions about Node. For more information, please follow other related articles on the PHP Chinese website!