Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common Node.js interview questions?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the common Node.js interview questions". In the daily operation, I believe many people have doubts about the common Node.js interview questions. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "what are the common Node.js interview questions?" Next, please follow the editor to study!

1. What is the difference between Node.js and JavaScript?

two。 When do you use Node.js?

Node.js is asynchronous, event-driven, non-blocking, and single-threaded, making it a perfect candidate for developing the following applications:

Real-time applications, such as chat and applications that provide real-time updates

A streaming application that streams video or other multimedia content to a large audience

Other Icano-intensive applications, such as collaboration platforms

Network backend that follows the micro-service architecture

However, the nature of Node.js makes it not an ideal choice for other types of applications. Applications that perform CPU-intensive tasks, such as complex mathematical calculations, do not perform well with CPU because Node.js is single-threaded.

If you want to know more about this, please check out our article Node.js architecture and when to use it in the project.

3. What did EventEmitter do?

Events emitted by any object in Node.js are instances of the EventEmitter class, just like the http module.

All EventEmitter classes can use the eventEmitter.on () function to attach event listeners to events. Then once such an event is captured, its listeners are called one by one synchronously.

Const events = require ("events"); const eventEmitter = new events.EventEmitter (); const eventListener = function () {console.log ("event triggered");} eventEmitter.on ("emitted", eventListener); eventEmitter.emit ("emitted")

4. What is the event loop?

A single-threaded Node.js must be non-blocking to prevent threads from blocking tasks that take a long time to complete, and the event loop is responsible for implementing this non-blocking behavior, which uses application threads to schedule pending tasks.

Node.js handles the response returned by the asynchronous function through a callback when the task is completed. Similar to the event that creates a task, an event is emitted after the task is completed. Node.js adds events that need to be handled to the event queue.

The event loop iterates over the events in the event queue and arranges when to execute its associated callback function.

5. What is stream?

A Stream stream is a pipeline that reads or writes data from a source and transfers it to a continuous stream destination. There are four types:

Readable

Writable

Readable and writable

Write first, then read it

Each stream is also an EventEmitter. This means that the stream object can have no data on the stream, have available data on the stream, or emit events when the program refreshes.

Const fs = require ("fs"); const readableStream = fs.createReadStream ("test.txt"); let content = ""; readableStream.on ("data", (chunk) = > {content + = chunk;}); readableStream.on ("end", () = > {console.log (content);})

6. What's the difference between readFile and createReadStream functions?

The readFile function reads the entire contents of the file asynchronously, stores it in memory, and then passes it to the user.

CreateReadStream uses a readable stream to read files block by block instead of storing them all in memory.

Compared to readFile, createReadStream uses less memory and faster speed to optimize file read operations. If the file is quite large, the user does not have to wait a long time until the entire content is read, because small chunks of content are sent to the user first.

Const fs = require ("fs"); fs.readFile ("test.txt", (err, content) = > {console.log (content);})

7. How do I handle uncaught exceptions in Node.js?

We can catch uncaught exceptions in the application at the process level. To do this, attach the listener to the process global object:

Process.on ("uncaughtException", (err) = > {console.log ("exception caught:", err);})

8. Can Node.js make full use of multi-core processors?

Node.js applications are always single-threaded, and applications can use only one processor even if they run on a multi-core processor.

But Cluster, one of the core modules of Node.js, supports Node.js applications to open multiple cores, allowing us to create multiple working processes that can run in parallel on multiple kernels and share a single port to listen for events.

Each process uses IPC to communicate with the main thread and pass the server handle to other processes as needed. The main process can listen on the port itself and pass each new connection to the child process in a circular manner, or it can assign the port to the child process to listen for requests.

9. What is the reactor design pattern?

The reactor design pattern is that Node.js appends callback functions (handlers) to each Imax O operation and then submits the handler to the demultiplexer when the request is created.

The demultiplexer collects each Imax O request made in the application and queues them as events in the queue. This queue is what we call the event queue. After queuing the event, the demultiplexer returns control of the application thread.

At the same time, the event loop iterates through each event in the event queue and invokes an additional callback to handle the event response.

This is the reactor mode used in Node.js.

10. What are the benefits of single-threading over multithreaded network backends?

Although Node.js is single-threaded, most programming languages for back-end development provide multithreading to handle application operations.

Why is single threading good for back-end development?

It is easier for developers to implement applications. Our applications do not suddenly encounter unexpected competitive conditions in the production process.

Single-threaded applications are easy to extend.

They can provide services with a large number of user requests received at a time without delay. In contrast, when the traffic is large, the multithreaded backend must wait for the thread in the thread pool to be released in order to serve the user request. With the non-blocking nature of Node.js, user requests do not hang on a single thread for too long (only if the operation is not CPU-intensive).

11. What is REPL?

REPL stands for Read Eval Print Loop and is a virtual environment in which you can easily run programming languages. Node.js comes with a built-in REPL to run JavaScript code, similar to the console we use to run JavaScript code in browsers.

To start Node.js REPL, simply run node on the command line, then write a line of JavaScript code, and you can see its output on the next line.

12. What's the difference between process.nextTick and setImmediate?

The callback passed to the setImmediate function is executed in the next iteration on the event queue.

On the other hand, the callback is passed to process.nextTick for execution before the next iteration and after the currently running operation in the program is completed. When the application starts, call its callback before you start traversing the event queue.

Therefore, the callback process.nextTick is always called before setImmediate.

The following code snippet:

SetImmediate (() = > {console.log ("first");}) process.nextTick (() = > {console.log ("second");}) console.log ("third")

Will be output sequentially:

Third second first

13. What is stub?

When testing an application using stub to simulate the behavior of a given component or module, you can focus on the part of the code you want to test. By using stub instead of test-independent components, you don't have to worry about external components affecting the results.

For example, if the component you are testing has a file read operation before the part of the expected test, you can use stub to simulate that behavior and return the simulated content without actually reading the file.

In Node.js, we use a library like Sinon to implement it. Sinon replaces some part of the code in the test, reducing the complexity of the test item writing https://sinonjs.org).

14. Why is it a good practice to separate "application" and "server" in express?

By separating the application from the server in Express, you can separate the API implementation from the network-related configuration. Executing API tests without network calls ensures faster test execution and better code coverage metrics.

To achieve this separation, you should declare API and server in a separate file, corresponding to app.js and server.js:

/ / app.js const express = require ("express"); const app = express (); app.use ("/", index); app.use ("/ contact", contact); app.use ("/ user", user); module.exports = app; / / server.js const http = require ("http"); const app = require ("/ app"); app.set ('port', process.env.PORT); const httphttp = http.createServer (app)

15. What are yarn and npm? Why use yarn instead of npm?

Npm is the default package manager that comes with Node.js. It has a large public and private database, which is stored in the database of npm registry. (translator's note, the official default central library http://registry.npmjs.org/, domestic Taobao mirror http://registry.npm.taobao.org/), users can access the database through the npm command line. With the help of npm, users can easily manage dependencies in a project.

Yarn is also a package manager to address some of the shortcomings of npm. Yarn relies on the npm registry to provide users with access to packages. The underlying structure of yarn is based on npm, and if you migrate from npm to yarn, the project structure and workflow do not need to be changed significantly.

As mentioned earlier, in some cases, yarn provides better functionality than npm. Unlike npm, it caches every package downloaded without having to download it again.

Provide better security by verifying the integrity of packages, ensuring that packages running on one system work in exactly the same way in any other system, which is why yarn is chosen over npm for package management.

At this point, the study of "what are the common Node.js interview questions" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report