node_notes
node_notes
Node.js is built on top of Google's V8 JavaScript engine, which is also used by Google
Chrome browser to execute JavaScript code.
When a Node.js application starts, it creates a single-threaded event loop that listens for
incoming requests.
When a request comes in, Node.js creates a new event and adds it to the event loop.
The event loop then processes the event and triggers the corresponding callback function
to handle the request.
While the callback function is processing the request, the event loop continues to listen for
new requests and events.
Node.js uses non-blocking I/O to handle requests and events, which means that it doesn't
wait for a request to finish before moving on to the next one.
This makes Node.js very efficient and scalable, since it can handle a large number of
requests and events simultaneously without getting bogged down.
Node.js also includes a number of built-in modules that make it easy to perform common
server-side tasks, such as reading and writing files, interacting with databases, and creating
HTTP servers.
Overall, Node.js is designed to be fast, lightweight, and scalable, making it a popular choice
for building high-performance web applications and server-side APIs.
fs (File System) module: This module provides methods for reading and writing files,
creating and deleting directories, and performing other file system operations.
http module: This module provides methods for creating HTTP servers and clients, sending
HTTP requests, and handling HTTP responses.
path module: This module provides methods for working with file and directory paths, such
as joining and resolving paths, getting the file extension, and getting the directory name.
os (Operating System) module: This module provides methods for retrieving information
about the operating system, such as the amount of free memory, the CPU architecture, and
the hostname.
util (Utility) module: This module provides various utility functions that can be used for
debugging, formatting, and other purposes. For example, it includes the util.inspect()
function for inspecting objects and the util.format() function for formatting strings.
To use a core module in a Node.js application, you simply need to require it using the
require() function. For example, to use the fs module to read a file, you could do the
following:
const fs = require('fs');
fs.readFile('myfile.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
In this example, the fs module is required using require(), and the readFile() function is
used to read the contents of the myfile.txt file. The contents of the file are then output to
the console using console.log().
Answer: In Node.js, streams are a way to handle data that is read from or written to a source
in a continuous and efficient manner. Streams are used to process large amounts of data,
especially when reading from or writing to files or network sockets.
Readable streams: Readable streams are used for reading data from a source. They emit the
'data' event when new data is available, and the 'end' event when there is no more data to
be read. Examples of readable streams include reading from a file or receiving data from a
network socket.
Writable streams: Writable streams are used for writing data to a destination. They have a
write() method for writing data, and the end() method to indicate that no more data will be
written. Examples of writable streams include writing to a file or sending data over a
network socket.
Duplex streams: Duplex streams are used for bidirectional communication, meaning that
they can both read and write data. Examples of duplex streams include TCP sockets and
WebSockets.
Transform streams: Transform streams are a type of duplex stream that allows for data to
be transformed as it is being read or written. They have both a write() method and a read()
method, and can be used for tasks such as compression or encryption.
Here's an example of using a readable stream to read data from a file and pipe it to a
writable stream to write it to another file:
const fs = require('fs');
readStream.pipe(writeStream);
In this example, a readable stream is created using the createReadStream() method, and a
writable stream is created using the createWriteStream() method. The pipe() method is then
used to connect the two streams, which causes the data to be read from the input file and
written to the output file.
One of the main advantages of using streams in Node.js is that they allow for processing
of large amounts of data in a memory-efficient way. Rather than reading or writing the
entire contents of a file or network socket at once, streams process the data in smaller
chunks, known as "chunks" or "buffers". This can help to reduce memory usage and
improve performance.
Streams in Node.js are implemented using the EventEmitter pattern, which means that they
emit events that can be listened to using event listeners. For example, a readable stream
emits a 'data' event when new data is available, and a 'end' event when there is no more
data to be read.
In addition to the four main types of streams mentioned earlier, Node.js also provides
several built-in transform streams that can be used for common tasks such as compression,
encryption, and JSON parsing.
2) crypto module: Provides encryption and decryption using various algorithms, such as
AES and RSA.
3) JSONStream module: Provides a way to parse and stringify JSON data in a streaming
manner.
4) split module: Splits input data into chunks based on a delimiter, such as a newline
character.
Overall, Node.js streams provide a powerful and flexible way to handle data in a streaming
manner, and can be used for a wide range of tasks, from reading and writing files to
communicating over network sockets.
REPL stands for Read-Eval-Print Loop. It is an interactive programming environment that allows
users to enter commands and see the results immediately. In a REPL, the user types in a command,
and the system reads the command, evaluates it, prints the result, and then waits for the next
command.
Read: When the user types in a command, the REPL reads it and parses it as JavaScript code.
Eval: The REPL then evaluates the code and returns the result. This could be a value, an error
message, or nothing at all.
Print: The result of the evaluated code is then printed to the console.
Loop: The REPL then goes back to the beginning, waiting for the user to enter another command.
The Node.js REPL can be accessed by running the node command in the terminal without any
arguments. Once in the REPL, the user can enter any valid JavaScript code, including defining
variables, functions, and control flow statements.
Q 5 How to check already installed dependencies which are globally installed using npm?
Answer: To check the globally installed dependencies using npm, you can use the npm list -g
command in your terminal. This will display a list of all the globally installed packages and their
versions.
Here are the steps to check the globally installed dependencies using npm:
You can also use the npm list -g --depth 0 command to display only the top-level globally installed
packages without their dependencies. This can be useful if you only want to see the list of packages
you have installed globally, without all the additional information about their dependencies.
Answer: The fs (file system) module in Node.js provides both synchronous and asynchronous
methods for working with files and directories.
Synchronous methods are blocking, which means that the program execution is blocked until the
operation is completed. When a synchronous method is called, the program waits until the
operation is finished before moving on to the next line of code. Synchronous methods have the
advantage of simplicity and a straightforward execution flow, but they can also cause performance
issues if used improperly, especially when dealing with large files or directories.
Here's an example of using the synchronous method fs.readFileSync() to read a file and return its
contents as a string:
const fs = require('fs');
try {
console.log(data);
} catch (err) {
console.error(err);
In this example, the program will wait until the contents of the file are read before moving on to
the next line of code.
Asynchronous methods, on the other hand, are non-blocking and allow the program to continue
executing while the operation is being performed in the background. When an asynchronous
method is called, the program moves on to the next line of code without waiting for the operation
to complete. Instead, the operation runs in the background and, once completed, triggers a callback
function to handle the results. Asynchronous methods have the advantage of not blocking program
execution, which can be especially useful when dealing with large files or directories.
Here's an example of using the asynchronous method fs.readFile() to read a file and return its
contents as a string:
const fs = require('fs');
if (err) {
console.error(err);
} else {
console.log(data);
});
In this example, the program moves on to the next line of code after calling fs.readFile(), and the
contents of the file are read in the background. Once the operation is complete, the callback
function is triggered, which handles the results.
In summary, synchronous methods block program execution until the operation is complete, while
asynchronous methods allow program execution to continue while the operation is being
performed in the background. Asynchronous methods are generally preferred for I/O operations in
Node.js because they are more efficient and can provide better performance for larger files or
directories.
Answer: 1) Event loop : The event loop is a mechanism that continuously monitors the Node.js
process for events, such as user input or system events. When an event is detected, the event loop
adds it to an event queue and proceeds to check if there are any pending callbacks in the callback
queue. If there are any callbacks in the queue, the event loop will execute them in the order they
were added. This process is repeated continuously, with the event loop monitoring the event queue
and processing callbacks in the callback queue as necessary. The event loop is responsible for
handling all I/O operations, including network requests, file system operations, and other
asynchronous events.
Here's an example of using a callback with the fs.readFile() method to read a file and return its
contents as a string:
const fs = require('fs');
if (err) {
console.error(err);
} else {
console.log(data);
});
Answer: In Node.js, buffers can be created using the Buffer class. The Buffer class is a built-in
class in Node.js that allows you to work with binary data. Buffers are used to represent a fixed-
size sequence of bytes and can be used to store data such as images, audio, or video.
To create a buffer in Node.js, you can use one of the following methods:
1) Buffer.from(): This method creates a buffer from a string, an array of bytes, or an array-
like object.
const buffer = Buffer.from('hello world', 'utf8');
console.log(buffer);
2) Buffer.alloc(): This method creates a buffer of a specified size and fills it with zeros.
const buffer = Buffer.alloc(10);
console.log(buffer);
3) Buffer.allocUnsafe(): This method creates a buffer of a specified size, but the contents of
the buffer are not initialized. This method is faster than Buffer.alloc() but can be unsafe if
you do not initialize the buffer contents.
const buffer = Buffer.allocUnsafe(10);
console.log(buffer);
Answer: In Node.js, the data types are the same as in JavaScript. Here are the main data types in
Node.js:
1) Number: Represents numeric values. In Node.js, all numbers are represented as 64-bit
floating-point values.
2) String: Represents a sequence of characters. Strings can be created using single or double
quotes.
3) Boolean: Represents a value that is either true or false.
4) Null: Represents a value that is explicitly set to null.
5) Undefined: Represents a value that is not assigned a value.
6) Object: Represents a collection of key-value pairs. Objects can contain properties that are
either primitive values or other objects.
7) Array: Represents an ordered list of values. Arrays can contain values of any data type,
including other arrays and objects.
8) Buffer: Represents a fixed-size sequence of bytes.
Answer:
1) console: The console object is used to log information to the console or terminal. It provides
methods like log(), error(), warn(), etc.
2) process: The process object provides information about the current Node.js process, such
as the current working directory, environment variables, command-line arguments, and
more.
3) Buffer: The Buffer object is used to work with binary data. It is a global object that can be
used to create and manipulate binary data directly.
4) setInterval: The setInterval function is a global function that is used to execute a function
repeatedly at a specified interval.
5) setTimeout: The setTimeout function is a global function that is used to execute a function
after a specified delay.
6) global: The global object provides access to global variables and functions in Node.js. It
can be used to define variables and functions that are available throughout the application.
However, it is generally considered a best practice to avoid using the global object
whenever possible.