This article brings you a summary of the interview questions about Node.js (with answers). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
##Translator’s note: From ECMAScript standard, Node.js syntax and NPM From a module perspective, the development of Node.js is dizzying, so interview questions must also keep pace with the times.
- Original text: Node.js Interview Questions and Answers (2017 Edition)
- Translator: Fundebug
In order to ensure readability, this article uses free translation rather than literal translation.
Question
- What is the error-first callback function?
- How to avoid callback hell?
- What is Promise?
- What tools are used to ensure consistent coding style? Why is this so?
- What is a Stub? Give an example
- What is a test pyramid? Give an example
- Which HTTP framework do you like the most? Why?
- How do cookies prevent XSS attacks?
- How to ensure the security of dependencies?
Answer
1. What is an error-first callback function?
The Error-First Callback function is used to return errors and data at the same time. The first parameter returns an error and verifies that it is an error; the other parameters are used to return data.
fs.readFile(filePath, function(err, data)
{
if (err)
{
// 处理错误
return console.log(err);
}
console.log(data);
});
Copy after login
2. How to avoid callback hell?
You can avoid callback hell in the following ways:
- Modularization: Convert callback functions into independent functions
- Use process Control library, such as aync
- Use Promise
- Use aync/await (refer to 6 reasons why Async/Await replaces Promise)
3. What is Promise?
Promise can help us better handle asynchronous operations. In the example below, the result string will be printed after 100ms.
catch is used for error handling. Multiple Promises can be chained.
new Promise((resolve, reject) =>
{
setTimeout(() =>
{
resolve('result');
}, 100)
})
.then(console.log)
.catch(console.error);
Copy after login
4. What tools are used to ensure consistent coding style? Why is this so?
When collaborating in a team, it is very important to ensure a consistent coding style so that team members can modify the code faster without having to adapt to a new style every time. These tools can help us:
If you are interested, you can refer to JavaScript Clean Coding
5. What is Stub? Give an example
Stub is used to simulate the behavior of modules. When testing, Stubs can return simulated results for function calls. For example, when we write a file, we don't actually need to actually write it.
var fs = require('fs');
var writeFileStub = sinon.stub(fs, 'writeFile', function(path, data, cb)
{
return cb(null);
});
expect(writeFileStub).to.be.called;
writeFileStub.restore();
Copy after login
6. What is the testing pyramid? For example, the
test pyramid reflects the proportion of
unit tests, integration tests and end-to-end tests that need to be written:
When testing the HTTP interface, it should look like this:
- Many unit tests, testing each module separately (dependencies require stub )
- Fewer integration tests, test the interaction between various modules (dependencies cannot be stub)
- Few end-to-end tests, go Call the real interface (dependencies cannot be stub)
7. Which HTTP framework do you like best? Why?
The standard answer to this question. The advantages and disadvantages of the framework need to be described so that it reflects the developer's familiarity with the framework.
8. How do cookies prevent XSS attacks?
XSS (Cross-Site Scripting, cross-site scripting attack) means that the attacker inserts JavaScript scripts into the returned HTML. To mitigate these attacks,
set-cookie needs to be configured in the HTTP header:
The result should be like this:
Set-Cookie: sid=; HttpOnly. If you use Express, cookie-session is configured by default .
9. How to ensure the security of dependencies?
When writing a Node.js application, you are likely to rely on hundreds or thousands of modules. For example, if Express is used, it will directly depend on 27 modules. Therefore, manually checking all dependencies is impractical. The only way is to perform automated security checks on dependencies. There are these tools to choose from:
- npm outdated
- Trace by RisingStack
- NSP
- GreenKeeper
- Snyk
Additional Question
1. What’s wrong with this code?
new Promise((resolve, reject) =>
{
throw new Error('error')
})
.then(console.log)
Copy after login
thenThere is no catch after that. This way, errors will be ignored. You can solve the problem like this:
new Promise((resolve, reject) =>
{
throw new Error('error')
})
.then(console.log).catch(console.error)
Copy after login
调试一个大型的项目时,可以使用监控unhandledRejection事件来捕获所有未处理的Promise错误:
process.on('unhandledRejection', (err) =>
{
console.log(err)
})
Copy after login
2. 这段代码有什么问题?
function checkApiKey(apiKeyFromDb, apiKeyReceived)
{
if (apiKeyFromDb === apiKeyReceived)
{
return true
}
return false
}
Copy after login
比较密码时,不能泄露任何信息,因此比较必须在固定时间完成。否则,可以使用timing attacks来攻击你的应用。为什么会这样呢?Node.js使用V8引擎,它会从性能角度优化代码。它会逐个比较字符串的字母,一旦发现不匹配时就停止比较。当攻击者的密码更准确时,比较的时间越长。因此,攻击者可以通过比较的时间长短来判断密码的正确性。使用cryptiles可以解决这个问题:
function checkApiKey(apiKeyFromDb, apiKeyReceived)
{
return cryptiles.fixedTimeComparison(apiKeyFromDb, apiKeyReceived)
}
Copy after login
3. 这段代码的输出是什么?
Promise.resolve(1)
.then((x) => x + 1)
.then((x) => { throw new Error('My Error') })
.catch(() => 1)
.then((x) => x + 1)
.then((x) => console.log(x))
.catch(console.error)
Copy after login
答案是2,逐行解释如下:
创建新的Promise,resolve值为1。
x为1,加1之后返回2。
x为2,但是没有用到。抛出一个错误。
捕获错误,但是没有处理。返回1。
x为1,加1之后返回2。
x为2,打印2。
不会执行,因为没有错误抛出。
The above is the detailed content of Summary of Node.js interview questions (with answers). For more information, please follow other related articles on the PHP Chinese website!