📜  libuv nodejs - Javascript (1)

📅  最后修改于: 2023-12-03 15:02:41.050000             🧑  作者: Mango

Libuv Node.js - JavaScript

Libuv is a C library that provides an event loop and other core functionalities for building networking and server-side applications. Node.js uses libuv to provide asynchronous I/O and event-driven programming.

Asynchronous I/O

Node.js is known for its asynchronous I/O and event-driven programming model. With asynchronous I/O, the application can continue executing other tasks while waiting for I/O operations (such as network requests or file access) to complete. This allows for better resource utilization and more responsive applications.

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200);
  res.end('Hello, world!');
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

In this example, the createServer function creates a server that listens for HTTP requests on port 3000. When a request is received, the callback function is called with the req (request) and res (response) objects. The res.writeHead and res.end functions are used to send a response back to the client. Meanwhile, the application can continue running and handling other tasks.

Event-driven programming

Node.js also uses an event-driven programming model. Functions are registered as event listeners and are invoked when the corresponding event occurs.

process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
  const chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write(`data: ${chunk}`);
  }
});

process.stdin.on('end', () => {
  process.stdout.write('end');
});

In this example, the process.stdin object is an EventEmitter that emits the readable event when there is data to be read from the standard input stream. The callback function registered with on('readable', ...) reads the data from the stream and writes it to the standard output stream using process.stdout.write. When there is no more data to be read (i.e. the end of the stream has been reached), the end event is emitted and the callback function registered with on('end', ...) is called, which simply writes 'end' to the standard output stream.

Conclusion

Libuv and Node.js provide powerful tools for building fast, scalable, and responsive networking and server-side applications using JavaScript. With asynchronous I/O and event-driven programming, it is possible to handle a large number of simultaneous connections with ease.