1. What is NPM?
NPM (Node Package Manager) manages packages for Node.js. It provides an online registry for open-source modules and a CLI tool to install, update, or remove packages.
npm install express
Get the Preplance app for a seamless learning experience. Practice offline, get daily streaks, and stay ahead with real-time interview updates.
Get it on
Google Play
4.9/5 Rating on Store
Meta · Node Js
Practice Node Js questions specifically asked in Meta interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
80
Tagged for this company + subject
Company
Meta
View company-wise questions
Subject
Node Js
Explore topic-wise practice
Go through each question and its explanation. Use this page for targeted revision just before your Meta Node Js round.
NPM (Node Package Manager) manages packages for Node.js. It provides an online registry for open-source modules and a CLI tool to install, update, or remove packages.
npm install express
For complete preparation, combine this company + subject page with full company-wise practice and subject-wise practice. You can also explore other companies and topics from the links below.
Node.js uses a single thread to handle requests asynchronously. This approach prevents the overhead of managing multiple threads and allows it to scale efficiently with minimal memory usage through event-driven I/O operations.
Promises simplify asynchronous flow by chaining operations with `.then()` and handling errors with `.catch()`. They avoid nested callbacks, improve readability, and allow better error propagation.
I/O (Input/Output) refers to data transfer between a system and external resources like files, networks, or devices. Node.js optimizes I/O using non-blocking event-driven architecture to handle many concurrent operations efficiently.
The Event Loop is the core of Node.js’s asynchronous architecture. It continuously checks the event queue and executes callbacks or promises when their operations complete. It allows Node.js to handle thousands of requests on a single thread.
Use `npm install package-name` to add, `npm update package-name` to update, and `npm uninstall package-name` to remove a dependency.
npm install express npm update express npm uninstall express
package.json holds project metadata like name, version, dependencies, and scripts. It is created using `npm init` and allows npm to install and manage required packages for your project.
{ "name": "my-app", "dependencies": { "express": "^4.18.0" } }The Buffer class is used to handle binary data directly, especially in file streams or TCP connections. Buffers are similar to arrays of integers but represent raw memory. This allows efficient reading and writing of binary data.
const buf = Buffer.from('Hello');
console.log(buf.toString());Callback hell occurs when multiple asynchronous functions are nested within each other, creating deep and unreadable code. It can be solved by using Promises or async/await for cleaner control flow.
// Callback Hell Example
fs.readFile('a.txt', () => {
fs.readFile('b.txt', () => {
fs.readFile('c.txt', () => {
console.log('done');
});
});
});Both create new processes. `spawn()` launches a new process with a given command. `fork()` is a special case of `spawn()` that creates a new Node.js instance for parallel execution, ideal for running multiple workers.
const { fork, spawn } = require('child_process');
const child = fork('worker.js'); // new Node process
const run = spawn('ls', ['-lh']); // system commandUse the `fs.open()` method to open a file. It takes a filename, flag (like 'r' for read or 'w' for write), and a callback. Always handle errors to avoid crashes.
const fs = require('fs');
fs.open('example.txt', 'r', (err, fd) => {
if (err) throw err;
console.log('File opened successfully');
});The Reactor Pattern is the design model behind Node.js’s non-blocking I/O system. It uses an event demultiplexer that listens for events and dispatches them to handlers asynchronously, improving performance and scalability.
The Test Pyramid represents the ideal balance of test types: more unit tests at the bottom, fewer integration tests in the middle, and even fewer end-to-end tests at the top. It ensures faster, stable, and maintainable testing strategies.
Node.js uses Google’s V8 engine because it compiles JavaScript directly into machine code for high performance. It supports just-in-time (JIT) compilation, making Node.js fast and efficient for both server and network operations.
Common HTTP request methods include: GET (retrieve data), POST (create or modify), PUT (update), DELETE (remove), and PATCH (partial update). Node’s `http` and Express frameworks support them all.
Use `fs.stat()` to get metadata like size, creation date, and modification time. It’s asynchronous and part of the core `fs` module.
const fs=require('fs');
fs.stat('file.txt',(err,stats)=>console.log(stats.size));The assert module helps test conditions in code. It throws errors if an expression evaluates to false, making it useful for debugging and creating unit tests in Node.js.
const assert = require('assert');
assert.strictEqual(2 + 2, 4);Express simplifies HTTP server creation and routing. It handles requests, middleware, and responses easily, making it ideal for APIs and full-stack apps. It’s fast, minimal, and widely supported.
The connect module provides a middleware framework for handling HTTP requests. It’s the foundation of Express. Developers can plug in middleware for cookies, sessions, authentication, and error handling.
const connect = require('connect');
const app = connect();
app.use((req,res)=>{res.end('Hello Connect');});
app.listen(3000);LTS stands for Long-Term Support. These Node.js versions receive stability, security, and bug fixes for about 30 months, making them suitable for production environments.
module.exports allows functions, objects, or values to be shared between files. It’s used with require() to import exported members into other modules.
// math.js
module.exports.add=(a,b)=>a+b;
// app.js
const { add }=require('./math');
console.log(add(2,3));ESLint is a static code analysis tool that identifies syntax issues, enforces coding standards, and improves code quality. It helps keep a consistent style and catches bugs early.
REPL stands for Read–Eval–Print–Loop. It is an interactive shell that executes JavaScript code line by line. It helps developers test and debug quickly. • Read – reads user input • Eval – evaluates input • Print – outputs result • Loop – waits for new input again.
node > let x = 10; x * 2 20
WebSockets enable full-duplex (two-way) communication between client and server. They maintain an open connection for real-time updates (e.g., chats, games). Implemented using `ws` or `socket.io` libraries.
const WebSocket=require('ws');
const wss=new WebSocket.Server({port:8080});
wss.on('connection',ws=>ws.send('Connected!'));CORS (Cross-Origin Resource Sharing) enables web apps running on one domain to access resources from another. The `cors` npm package sets headers to allow or restrict requests from other origins.
const cors=require('cors');
app.use(cors({origin:'*'}));Tools like ESLint and Prettier enforce consistent formatting and code quality. They integrate with editors and CI pipelines to prevent syntax errors and maintain readable codebases.
Node.js is fast, lightweight, and highly scalable. It supports asynchronous non-blocking operations, making it perfect for real-time and I/O-heavy applications. It uses a single-threaded event loop model, reducing overhead and improving performance.
Frontend (client-side) involves what users see and interact with—HTML, CSS, JavaScript, React, etc. Backend (server-side) handles data, APIs, and server logic using languages like Node.js, Python, or Java.
module.exports defines what values or functions a module exposes to other files. It allows encapsulation and reusability of code across different parts of an application.
// math.js
module.exports.add = (a,b)=>a+b;
// app.js
const math=require('./math');
console.log(math.add(2,3));EventEmitter is a core module that allows objects to emit and listen for events. It forms the base for asynchronous communication in Node.js. You can register listeners with `.on()` and trigger them with `.emit()`.
const EventEmitter=require('events');
const emitter=new EventEmitter();
emitter.on('greet',()=>console.log('Hello!'));
emitter.emit('greet');Node.js provides asynchronous (non-blocking) and synchronous (blocking) APIs. Asynchronous APIs allow other code to execute while waiting for results, whereas synchronous APIs block the event loop until completion.
Express.js is a minimal and flexible web framework built on Node.js. It simplifies handling routes, requests, and middleware to build RESTful APIs and web apps quickly.
Use the HTTP module, call `createServer()` with a callback that handles requests and responses, and listen on a port.
const http=require('http');
http.createServer((req,res)=>{
res.write('Hello World');
res.end();
}).listen(8080);All Node.js APIs are asynchronous, meaning they don’t block execution. The server can process other requests while waiting for one operation to finish. Results are handled using callbacks, promises, or async/await.
You can write async functions using `async` and `await`. The function waits for a Promise to resolve before executing the next line, making async code easy to read and debug.
async function getData(){
const res=await fetch('https://api.com');
const data=await res.json();
console.log(data);
}NODE_ENV is an environment variable that defines the runtime mode of your app, such as 'development', 'production', or 'test'. It helps configure logging, caching, and debugging behaviors accordingly.
if(process.env.NODE_ENV==='production'){console.log('Running in production');}Node.js provides global timing functions like `setTimeout`, `setInterval`, `setImmediate`, and `process.nextTick`. These schedule functions at different stages of the event loop for asynchronous control.
setTimeout(()=>console.log('Timeout'),1000);
setImmediate(()=>console.log('Immediate'));
process.nextTick(()=>console.log('Next Tick'));Node.js uses npm or yarn for package management. You can install third-party modules, manage dependencies via package.json, and use scripts for automation. `npm install` reads dependencies and installs them automatically.
npm install express npm list --depth=0
Node.js is fast, scalable, and event-driven. It handles many concurrent connections using non-blocking I/O, making it ideal for real-time applications. Its single-threaded model with the V8 engine ensures efficiency.
The async.queue() function takes a worker function (that processes tasks) and an optional concurrency limit. It allows you to process multiple tasks in parallel while controlling concurrency.
Synchronous functions block further code execution until completion. Asynchronous functions run in the background and use callbacks, promises, or async/await, allowing Node.js to handle many operations efficiently.
// Sync
const fs=require('fs');
fs.readFileSync('file.txt');
// Async
fs.readFile('file.txt',()=>console.log('Done'));Node.js uses non-blocking asynchronous I/O and an event-driven architecture. Instead of waiting for tasks like file reads or database calls, it delegates them to the event loop and continues executing other code.
Separating your app from the server simplifies testing, scaling, and deployment. The app handles routes and middleware, while the server handles network configuration and listening. This structure improves maintainability.
Node.js runs JavaScript on a single thread but can create child processes using `child_process` or worker threads. These allow parallel execution without blocking the event loop.
const { Worker } = require('worker_threads');
new Worker('./task.js');A thread pool is a collection of background threads used for heavy I/O operations like file access and compression. Node.js uses the libuv library to manage this pool and distribute tasks efficiently.
Clusters create multiple Node.js processes, each running on a CPU core. Worker threads, however, share memory within a single process. Workers are better for CPU-intensive tasks; clusters are ideal for scaling web servers.
Tracing collects information about function calls and system events to analyze performance. Node.js’s built-in tracing API and tools like Chrome DevTools help identify bottlenecks and optimize runtime behavior.
The crypto module enables secure data encryption, hashing, and signing. It supports algorithms like AES, RSA, and SHA, helping developers secure passwords, tokens, and sensitive data.
const crypto=require('crypto');
const hash=crypto.createHash('sha256').update('secret').digest('hex');
console.log(hash);NODE_ENV defines the environment in which the app runs — 'development', 'test', or 'production'. It controls configuration like logging, performance optimization, and debug settings. Production mode improves speed and disables verbose logs.
Node.js implements sandboxing to isolate code, uses TLS/SSL for encryption, environment variables for secrets, and libraries like Helmet for securing HTTP headers. Regular dependency audits also prevent known vulnerabilities.
Passport.js is a flexible authentication middleware for Node.js. It supports local logins and social logins (Google, Facebook, GitHub). It simplifies user authentication by using modular strategies.
const passport=require('passport');
app.post('/login',passport.authenticate('local'),(req,res)=>res.send('Logged in'));Yes. You can run `node inspect app.js` to debug applications. The built-in debugger allows step-by-step execution, variable inspection, and breakpoints using Chrome DevTools or VSCode integration.
node inspect index.js // open chrome://inspect for debugging
You can wrap asynchronous code in a try-catch block or use middleware that automatically catches rejections. For production apps, centralized handlers prevent crashes and maintain clean logs.
try {
const data = await getData();
} catch (err) {
console.error('Error fetching data', err);
}Environment variables store secrets like API keys and database URLs. You can use `process.env` or a library like dotenv to load them from a .env file. Never hardcode secrets in code.
require('dotenv').config();
const dbUrl = process.env.DATABASE_URL;Mocha is a JavaScript test framework that runs in Node.js and browsers. Tests are written using describe/it blocks and assertions from Chai or Assert. Run with `npx mocha` or configure in npm scripts.
const assert=require('assert');
describe('Array',()=>{
it('should return -1 when value not found',()=>{
assert.equal([1,2,3].indexOf(4),-1);
});
});Jest provides zero-configuration testing with built-in mocks, snapshot testing, and parallel execution. It’s widely used for both backend and frontend testing in JavaScript projects.
test('adds 2 + 2',()=>{
expect(2+2).toBe(4);
});Static analysis tools like ESLint and TypeScript detect errors before runtime. They help enforce coding standards and reduce defects through early feedback during development.
Use packages like `express-rate-limit` or Redis-based counters to restrict requests per user or IP. It protects servers from abuse and ensures fair usage.
import rateLimit from 'express-rate-limit';
const limiter=rateLimit({windowMs:60000,max:100});
app.use(limiter);Load balancing can be achieved with Nginx, HAProxy, or PM2 cluster mode. It distributes incoming requests evenly across Node.js instances to prevent overload.
Use the Chrome DevTools Heap Snapshot or tools like `clinic heapprofiler` to track object growth. Common causes are global variables, unclosed streams, or forgotten timers.
Use HTTPS, sanitize input, apply Helmet middleware, rate-limit endpoints, and validate JWTs. Avoid eval(), keep dependencies updated, and store secrets in environment variables.
The Timers module allows scheduling of code execution after a specified time. It provides functions like `setTimeout()`, `setInterval()`, and `setImmediate()` to run callbacks asynchronously in future event loop phases.
setTimeout(()=>console.log('After delay'),1000);
setImmediate(()=>console.log('Next phase'));The util module provides helpful functions for debugging and inheritance. Common methods include `util.inherits()` for classical inheritance, `util.promisify()` to convert callbacks into Promises, and `util.format()` for string formatting.
const util=require('util');
const wait=util.promisify(setTimeout);
await wait(1000);Control flow refers to managing asynchronous operations’ order and results. Since Node.js doesn’t block execution, control flow ensures callbacks, promises, and async/await handle dependencies correctly in async code.
You can use the global `process.argv` array to read CLI arguments passed to the script. Arguments start from index 2, as the first two are node executable and script path.
console.log(process.argv.slice(2)); // node app.js arg1 arg2
Control flow manages async function calls by defining clear execution order. It executes one function, waits for its callback or promise, and then triggers the next one. Libraries like `async` simplify this with series or parallel task control.
Node.js is faster, supports asynchronous I/O, and allows using JavaScript both on frontend and backend. It’s lightweight, scalable, and ideal for data-intensive applications. In contrast, Java/PHP rely on multi-threaded blocking architectures.
Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome’s V8 engine. It allows running JavaScript on the server side instead of just in the browser. It is commonly used for building web servers, APIs, streaming applications, and real-time apps like chat or online games.
Node.js handles concurrency via its Event Loop and Worker Pool. The Event Loop continuously listens for new events, while the Worker Pool executes I/O or CPU-intensive operations in the background without blocking the main thread.
First-class functions are functions that can be stored in variables, passed as arguments, or returned from other functions. Node.js uses this concept extensively for callbacks and asynchronous handling.
function greet(){return 'Hello';}
function run(fn){console.log(fn());}
run(greet);Node.js supports all standard HTTP request methods such as GET (fetch data), POST (create data), PUT (update data), DELETE (remove data), PATCH (partial update), and HEAD (metadata only). These can be implemented using the `http` or `express` modules.
app.get('/users',(req,res)=>res.send('List'));
app.post('/users',(req,res)=>res.send('Created'));Use caching (Redis or in-memory), pagination, compression, connection pooling, and asynchronous code. Avoid blocking calls, use async/await efficiently, and enable GZIP compression for responses. Profiling tools like Clinic.js help spot slow endpoints.
JWTs are signed tokens containing user data. The server verifies the token signature to authenticate users. JWTs are stateless and used for scalable authentication across APIs.
import jwt from 'jsonwebtoken';
const token = jwt.sign({id:1},'secret',{expiresIn:'1h'});
const decoded = jwt.verify(token,'secret');Modules are reusable JavaScript files that export specific functionality. Node.js includes built-in core modules like `fs`, `http`, `url`, and `stream`. Developers can also create custom modules using `module.exports`.
const fs = require('fs');
const data = fs.readFileSync('file.txt');Event-driven programming means the flow of the program is determined by events such as user actions or messages from other programs. In Node.js, events trigger callback functions through the EventEmitter system, allowing non-blocking, asynchronous behavior.
process.nextTick() executes a callback immediately after the current operation, before the next event loop iteration. setImmediate() schedules the callback for the next iteration of the event loop, after I/O events. nextTick() runs sooner.
process.nextTick(()=>console.log('Next Tick'));
setImmediate(()=>console.log('Immediate'));REPL stands for Read-Eval-Print Loop. It is a Node.js command-line tool that allows developers to quickly test code snippets. You can type JavaScript directly into the terminal, and Node.js will execute and return results immediately — useful for debugging and experimenting.
Libuv is the C library that powers Node.js’s event loop and asynchronous I/O operations. It handles non-blocking file I/O, DNS, and network operations across different operating systems, enabling Node to stay single-threaded yet highly concurrent.
Global objects are accessible anywhere in Node.js without importing them. Examples include `process`, `console`, `Buffer`, `__dirname`, and `setTimeout`. These objects provide environment info, logging, and system-level access.
Node.js uses try-catch for synchronous errors and callback or Promise rejection handlers for async code. Uncaught errors crash the process, so using centralized error middleware or process event handlers (`process.on('uncaughtException')`) ensures graceful recovery.
app.use((err,req,res,next)=>{
console.error(err.stack);
res.status(500).send('Something broke!');
});