Global Objects and the Process
In the browser, JavaScript has a global object called window. In Node.js, the main global object is process. It represents the running program itself. You can ask it things like:
process.argv— the words typed after thenodecommand, such as a file name.process.env— environment variables, which are settings your computer passes to programs.
Another handy one is console, which prints messages, and __dirname, which tells you the folder your file lives in.
Reading and Writing Files
Real programs need to save and load data. Node.js includes a tool called the fs module ("fs" stands for file system) that reads and writes files.
const { readFile } = require('node:fs/promises');
async function main() {
const text = await readFile('notes.txt', 'utf8');
console.log(text);
}
main();Working Asynchronously
Here is the key idea: reading a file takes time, so Node.js does not sit and wait. It starts the work, moves on, and comes back when the file is ready. This is called asynchronous code — "async" for short.
The modern way to write it is async/await. You mark a function as async, then use await to pause just that function until the work finishes, without freezing the whole program.
const { writeFile } = require('node:fs/promises');
async function main() {
await writeFile('notes.txt', 'Hello from Node.js!');
console.log('Saved.');
}
main();Handling Errors in Async Code
Files can be missing, disks can fail. With async/await, you handle problems with a normal try/catch block — the same tool used for ordinary JavaScript errors.
try {
const text = await readFile('missing.txt', 'utf8');
} catch (err) {
console.error('Could not read file:', err.message);
}Building Your First Web Server
A web server is a program that answers requests from browsers. Node.js has a built-in http module for this. Here is a complete, tiny server:
const http = require('node:http');
const server = http.createServer((req, res) => {
res.end('Hello, world!');
});
server.listen(3000);
console.log('Server running at http://localhost:3000');Run it with node server.js, then open http://localhost:3000 in your browser. You have just served a web page with no frameworks at all.
Show diagram source
flowchart LR
A[Browser] --> B[http module]
B --> C[Your handler function]
C --> D[Response sent back to browser]Exercise
What object represents the running Node.js program, and what does process.argv give you?
Show answer
The process object. process.argv gives the words typed after the node command, such as the script name and any extra arguments.
Spotted a mistake, or code that does not work?