0% found this document useful (0 votes)
23 views12 pages

Node Js Short Notes

Node js

Uploaded by

tempmailforamit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views12 pages

Node Js Short Notes

Node js

Uploaded by

tempmailforamit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

NODE.

js SHORT NOTES
1. Introduction to Node.js
- What is Node.js?: Node.js is a JavaScript runtime built on Chrome's V8
JavaScript engine. It allows developers to run JavaScript on the server side.
- Non-blocking I/O: Node.js uses asynchronous, event-driven architecture, making
it efficient for I/O-heavy tasks.
- Single-threaded: Although Node.js runs on a single thread, it handles multiple
requests concurrently via an event loop.

2. Modules
- Built-in modules: Node.js provides various built-in modules like `fs` (File System),
`http` (for creating servers), `path`, etc.
- CommonJS Modules: The module system in Node.js uses `require()` to import
and `module.exports` to export.
- npm (Node Package Manager): Tool for installing and managing third-party
packages.

3. File System (fs) Module


- Provides methods to interact with the file system, such as reading, writing,
updating, and deleting files.
- Operations:
- `fs.readFile()`
- `fs.writeFile()`
- `fs.appendFile()`
- `fs.unlink()`
- `fs.rename()`

4. HTTP Module
- Used to create a server in Node.js.
- Example:
```js
const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello World!');
res.end();
});
server.listen(3000);
```
- Request and Response Objects: Handle incoming HTTP requests and return
appropriate responses.

5. Express.js Framework
- What is Express?: A minimalistic web framework for Node.js that simplifies
server-side code.
- Routing: Use `app.get()`, `app.post()`, etc., to define routes.
- Middleware: Functions that process requests before reaching the endpoint.
Example: `app.use()`.
- Handling Forms and JSON Data: Parse incoming requests using middleware like
`body-parser`.

6. Event-driven Architecture
- Events and Event Emitter: Node.js uses an event-driven architecture where
certain functions (like file reads) emit events.
- EventEmitter Class: Events are handled using instances of the `EventEmitter`
class.
```js
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('event', () => { console.log('An event occurred!'); });
eventEmitter.emit('event');
```

7. Asynchronous Programming
- Callbacks: Functions passed as arguments to other functions, executed once an
async task is completed.
- Promises: An alternative to callbacks, providing a cleaner way to handle async
operations.
- Async/Await: Syntactic sugar over promises, making asynchronous code look
synchronous.

8. Streams
- What are Streams?: Streams are objects that allow reading or writing data
continuously.
- Types of Streams:
- Readable: `fs.createReadStream()`
- Writable: `fs.createWriteStream()`
- Duplex: Both readable and writable.
- Transform: Modifies the data as it is being read or written.
- Useful for handling large files.

9. Buffer
- What is Buffer?: Temporary storage for binary data, mainly used with streams.
- Buffer Class: Used to manipulate binary data in Node.js.

10. Working with Databases


- MongoDB: NoSQL database, often used with Node.js.
- Mongoose: ODM (Object Data Modeling) library for MongoDB, providing
schema-based data modeling.
- SQL Databases: Node.js can interact with SQL databases like MySQL,
PostgreSQL using libraries like `sequelize`, `pg`, `mysql`.

11. Error Handling


- Try-Catch: Handle synchronous errors.
- Error-first Callbacks: Node.js follows an error-first callback pattern, where the first
argument of the callback is an error object.
- Promise Error Handling: Use `.catch()` for errors in promises.
- Async/Await Error Handling: Use `try-catch` blocks to catch errors with async
functions.

12. Middleware in Express


- What is Middleware?: Functions that execute during the lifecycle of a request to
the server.
- Types of Middleware:
- Application-level: Bound to an instance of `express()`.
- Router-level: Bound to an instance of `express.Router()`.
- Error-handling Middleware: Takes four arguments `(err, req, res, next)` to
handle errors.

13. API Development


- RESTful APIs: Node.js is commonly used to create RESTful services.
- Routing in Express: Define routes for different HTTP methods (GET, POST,
PUT, DELETE).
- Handling JSON Data: Using `express.json()` middleware to parse JSON
requests.

14. Security in Node.js


- Helmet.js: Middleware that adds security-related HTTP headers.
- Rate Limiting: Control the rate of requests using tools like `express-rate-limit`.
- Input Validation and Sanitization: Use libraries like `validator` to prevent SQL
injection, XSS, etc.

15. Websockets
- What is WebSocket?: A protocol for two-way communication between the client
and server over a single, long-lived connection.
- Socket.io: Popular library for implementing WebSocket communication in
Node.js.
16. Testing in Node.js
- Mocha: A testing framework for Node.js.
- Chai: An assertion library used with Mocha for testing.
- Jest: Another popular testing framework, often used for both backend and
frontend.

17. Deployment
- PM2: A process manager to keep Node.js applications running.
- Docker: Used to containerize Node.js applications.
- Hosting Platforms: Deploy Node.js applications on services like Heroku, AWS,
Azure, and DigitalOcean.

18. Version Control and Managing Multiple Node Versions


- nvm (Node Version Manager): Tool for installing and managing multiple versions
of Node.js.

QUESTION AND ANSWERS

Basic Node.js Questions:

1. What is Node.js?
- Node.js is a JavaScript runtime built on Chrome's V8 engine, allowing JavaScript
to run server-side.

2. Is Node.js single-threaded or multi-threaded?


- Node.js is single-threaded with an event-driven, non-blocking architecture.

3. What is npm?
- npm (Node Package Manager) is a package manager for JavaScript, providing
access to thousands of packages for use in Node.js projects.
4. What is the global object in Node.js?
- `global` is the global object in Node.js, similar to `window` in a browser
environment.

5. What is the purpose of `require()` in Node.js?


- `require()` is used to load modules (built-in or user-defined) in Node.js.

6. How do you create a server in Node.js?


```js
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
server.listen(3000);
```

7. What is a callback function?


- A callback is a function passed as an argument to another function, which is
executed after an operation completes.

8. What is the event loop in Node.js?


- The event loop is the mechanism that allows Node.js to perform non-blocking I/O
operations despite being single-threaded by offloading operations to the system.

9. What is the role of the `fs` module in Node.js?


- The `fs` (File System) module allows Node.js to interact with the file system to
read, write, update, or delete files.

10. What is the difference between `readFileSync` and `readFile`?


- `readFileSync` is a synchronous method that blocks the execution until the file is
read, while `readFile` is asynchronous.
Intermediate Node.js Questions:

11. What are streams in Node.js?


- Streams are objects that let you read or write data continuously. They are useful
for handling large amounts of data.

12. What are the types of streams in Node.js?


- Readable, Writable, Duplex, and Transform streams.

13. What is middleware in Express.js?


- Middleware are functions that execute during the lifecycle of a request to the
server and can modify the request or response.

14. How does Node.js handle concurrency?


- Node.js uses an event loop and a single thread, handling concurrency via non-
blocking I/O and callbacks.

15. What is `module.exports`?


- `module.exports` is used to export variables, objects, or functions from a
module, making them available to other modules via `require()`.

16. What is a promise in Node.js?


- A promise is an object representing the eventual completion or failure of an
asynchronous operation.

17. What is async/await in Node.js?


- `async` and `await` are syntactic sugar for handling promises, making
asynchronous code look synchronous.

18. What is `process.nextTick()`?


- `process.nextTick()` schedules a callback function to be invoked in the next
iteration of the event loop, before any I/O tasks.

19. How do you handle errors in Node.js?


- Errors can be handled using `try-catch`, error-first callbacks, or `.catch()` for
promises.

20. What is the difference between `res.send()` and `res.json()` in Express?


- `res.send()` can send any type of response (HTML, JSON, plain text), while
`res.json()` is used to send a JSON response.

Advanced Node.js Questions:

21. What is the `cluster` module in Node.js?


- The `cluster` module enables the creation of child processes (workers) that
share the same server port to handle multiple requests concurrently.

22. What is the difference between process.env and process.argv?


- `process.env` contains environment variables, while `process.argv` contains the
command-line arguments passed when starting a Node.js process.

23. What is the purpose of the `buffer` in Node.js?


- `Buffer` is used to handle binary data in Node.js, especially when working with
streams or files.

24. How can you make a module globally accessible in Node.js?


- To make a module globally accessible, you can install it globally using `npm
install -g` or modify the `global` object.

25. What are worker threads in Node.js?


- Worker threads enable running JavaScript in parallel on multiple threads, useful
for CPU-intensive tasks.
26. What is the difference between `setImmediate()` and `setTimeout()`?
- `setImmediate()` executes a callback on the next iteration of the event loop,
while `setTimeout()` schedules execution after a minimum delay.

27. How do you connect Node.js to a MongoDB database?


- Use the MongoDB Node.js driver or an ODM like Mongoose.
```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testdb');
```

28. What is the purpose of `app.use()` in Express?


- `app.use()` is used to apply middleware functions to an Express application.

29. How does Node.js handle child processes?


- The `child_process` module in Node.js allows you to spawn child processes,
enabling parallel execution of tasks.

30. What is Helmet.js?


- Helmet.js is an Express middleware that helps secure apps by setting various
HTTP headers.

Node.js Security Questions:

31. What is CORS?


- CORS (Cross-Origin Resource Sharing) is a security feature that allows or
restricts resources on a web page to be requested from another domain.

32. How can you prevent SQL injection in Node.js?


- Use parameterized queries or an ORM (like Sequelize or Mongoose) to prevent
SQL injection.
33. What is CSRF?
- Cross-Site Request Forgery (CSRF) is an attack that forces a user to execute
unwanted actions on a web application.

34. How do you prevent CSRF attacks in Node.js?


- Use CSRF tokens (middleware like `csurf`) to verify requests’ authenticity.

35. How can you secure sensitive data in Node.js?


- Encrypt sensitive data using libraries like `crypto` and always store credentials in
environment variables.

36. What is rate limiting, and how can you implement it in Node.js?
- Rate limiting restricts the number of requests a client can make in a specific time
period, and it can be implemented using the `express-rate-limit` package.

37. What is input validation, and why is it important in Node.js?


- Input validation ensures that user data is correct and safe. It helps prevent
common attacks like SQL injection and XSS (Cross-Site Scripting).

38. What is XSS, and how can you prevent it?


- XSS (Cross-Site Scripting) is an attack that injects malicious scripts into web
pages. You can prevent it by validating and sanitizing input, escaping HTML
characters, and using libraries like `xss-clean`.

39. How do you encrypt passwords in Node.js?


- Use hashing algorithms like bcrypt to securely store passwords.
```js
const bcrypt = require('bcrypt');
bcrypt.hash('password', saltRounds, function(err, hash) { });
```
40. How can you handle user authentication in Node.js?
- Use JWT (JSON Web Token) or Passport.js for handling authentication.

Node.js Ecosystem Questions:

41. What is the role of Mongoose in a Node.js application?


- Mongoose is an ODM (Object Data Modeling) library for MongoDB, providing a
schema-based solution to model your application data.

42. What is the difference between Node.js and Deno?


- Deno is a secure runtime for JavaScript and TypeScript, with features like built-
in TypeScript support, while Node.js focuses on JavaScript with a large ecosystem.

43. What is Socket.io?


- Socket.io is a library that enables real-time, bidirectional communication
between clients and servers over WebSocket or polling.

44. What is Sequelize?


- Sequelize is a promise-based Node.js ORM for SQL databases like MySQL,
PostgreSQL, SQLite, and others.

45. What is Nodemon?


- Nodemon is a tool that automatically restarts a Node.js server when file changes
are detected.

46. How do you test a Node.js application?


- Use testing libraries like Mocha, Chai, or Jest to write unit and integration tests.
47. What is the difference between synchronous and asynchronous functions in
Node.js?
- Synchronous functions block the execution of subsequent code until they
complete, while asynchronous functions do not block and use callbacks, promises,
or async/await to manage execution.

48. How can you debug a Node.js application?


- Use built-in debugging tools like `console.log()`, or more advanced tools like the
Node.js Inspector and `node --inspect`.

49. What is clustering in Node.js?


- Clustering allows you to take advantage of multi-core systems by running
multiple instances of a Node.js application, each handling incoming requests
concurrently.

50. What are the benefits of using Node.js?


- Fast execution (thanks to V8 engine), non-blocking I/O for scalability, large
community and ecosystem (npm), and JavaScript support on both client and server.

You might also like