Home > Web Front-end > JS Tutorial > body text

Share some front-end interview questions about Node

青灯夜游
Release: 2020-12-10 17:53:27
forward
2708 people have browsed it

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.

Share some front-end interview questions about Node

Related recommendations: "nodejs Tutorial"

Node front-end interview questions

**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 (javascriptimplementation) >> c binding>> libuv CAes http.

3. What core modules does node have?

EventEmitter, Stream, FS, Net和全局对象
Copy after login

4. What global objects does node have?

process, console, Buffer和exports
Copy after login

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
Copy after login

6. What are the common methods of console?

console.log/console.info, console.error/console.warning, console.time/console.timeEnd, console.trace, console.table
Copy after login

7. What are the timing functions of node?

setTimeout/clearTimeout, setInterval/clearInterval, setImmediate/clearImmediate, process.nextTick
Copy after login

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?

BufferYes 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传递消息真方便!');
Copy after login

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'); 
});
Copy after login

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'); 
});
Copy after login

**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) Constructor

call Writable

2) Inherit 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作为输出源
Copy after login

21、内置的fs模块架构是什么样子的?

fs模块主要由下面几部分组成:

1) POSIX文件Wrapper,对应于操作系统的原生文件操作
2) 文件流 fs.createReadStreamfs.createWriteStream
3) 同步文件读写,fs.readFileSyncfs.writeFileSync
4) 异步文件读写, fs.readFilefs.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
Copy after login

**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是输出流 
// 这句的意思是将子进程的输出作为当前程序的输入流,然后重定向到当前程序的标准输出,即控制台
Copy after login

**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("我不要关怀,我要银民币!"); 
});
Copy after login

**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) memwatchheapdump获得内存快照进行对比,查找内存溢出

**41、有哪些常用方法可以防止程序崩溃? **

1) try-catch-finally
2) EventEmitter/Stream error事件处理
3) domain统一控制
4) jshint静态检查
5) jasmine/mocha进行单元测试

42、怎样调试node程序?

node --debug app.jsnode-inspector

43、async都有哪些常用方法,分别是怎么用?

async是一个js类库,它的目的是解决js中异常流程难以控制的问题.async不仅适用在node.js里,浏览器中也可以使用.
1) async.parallel并行执行完多个函数后,调用结束函数

async.parallel([ 
    function(){ ... }, 
    function(){ ... } 
], callback);
Copy after login
  1. async.series串行执行完多个函数后,调用结束函数
async.series([ 
    function(){ ... }, 
    function(){ ... } 
 ]);
Copy after login
  1. 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' 
});
Copy after login
  1. async.map异步执行多个数组,返回结果数组
async.map(['file1','file2','file3'], fs.stat, function(err, results){ 
  // results is now an array of stats for each file 
});
Copy after login
  1. async.filter异步过滤多个数组,返回结果数组
async.filter(['file1','file2','file3'], fs.exists, function(results){ 
  // results now equals an array of the existing files 
});
Copy after login

44、express项目的目录大致是什么样子的

app.js, package.json, bin/www, public, routes, views.
Copy after login

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() 结束response
res.json() 返回json 在这里插入代码片
res.jsonp() 返回jsonp
res.redirect() 重定向请求
res.render() 渲染模板
res.send() 返回多种形式数据
res.sendFile 返回文件
res.sendStatus() 返回状态

48、mongodb有哪些常用优化措施
类似传统数据库,索引和分区

49、mongoose是什么?有支持哪些特性?
mongoosemongodb的文档映射模型.主要由Schema, ModelInstance三个方面组成.
Schema就是定义数据类型,
Model就是把Schemajs类绑定到一起,
Instance就是一个对象实例.
常见mongoose操作有,save, update, find. findOne, findById, static方法等

50、redis支持哪些功能

set/get, mset/hset/hmset/hmget/hgetall/hkeys, sadd/smembers, publish/subscribe, expire
Copy after login

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();
Copy after login

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!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!