Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Your First Node.js Program
interview

Q1. How do you create and run your first Node.js program?
Create a file named app.js (or any name) and write:
console.log("Hello, Node.js!");
. Open terminal, navigate to the file location, and run: node app.js. The output "Hello, Node.js!" will appear in the console. This demonstrates that Node.js can execute JavaScript outside the browser.

Q2. How do you run a Node.js file with arguments?
You can pass arguments when running a Node.js script: node app.js arg1 arg2. Inside the script, access them via process.argv array. process.argv[0] is the node executable path, process.argv[1] is the script path, and subsequent elements are the arguments. Example:
console.log(process.argv[2])
prints first argument.

Q3. What is the difference between running JavaScript in browser vs Node.js?
In browser, JavaScript has access to DOM, window object, and browser APIs. In Node.js, there's no DOM; instead, you have access to server-side features like file system, networking, and process object. Both use the V8 engine, but the runtime environment and available APIs differ significantly.

Q4. How do you use global objects in Node.js?
Node.js provides global objects like __dirname (current directory), __filename (current file path), process (process information), and module (module information). You can use them without requiring any modules. For example:
console.log(__dirname)
prints the directory of the current file.

Q5. How do you create a simple HTTP server as your first program?
Use the built-in http module:
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }); server.listen(3000, () => console.log('Server running'));
Then visit http://localhost:3000.