1. Basics
- Installation: Download from Node.js official website.
- Check Version:
node -v
npm -v
2. Creating a Simple Server
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
3. File System Operations
- Read File:
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
- Write File:
fs.writeFile('example.txt', 'Hello, Node!', (err) => { if (err) throw err; console.log('File has been saved!'); });
4. Modules
- Create a Module:
// myModule.js const greeting = (name) => `Hello, ${name}!`; module.exports = greeting;
- Import a Module:
const greeting = require('./myModule'); console.log(greeting('World'));
5. NPM Commands
- Initialize Project:
- Install Package:
npm install package-name
- Uninstall Package:
npm uninstall package-name
- List Installed Packages:
6. Asynchronous Programming
- Callback Example:
function fetchData(callback) { setTimeout(() => { callback('Data fetched'); }, 1000); } fetchData((data) => { console.log(data); });
- Promises:
const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve('Data fetched'); }, 1000); }); }; fetchData().then(data => console.log(data));
- Async/Await:
const fetchData = async () => { return 'Data fetched'; }; const getData = async () => { const data = await fetchData(); console.log(data); }; getData();
7. Express.js Framework
- Setting Up Express:
npm install express
- Basic Express Server:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, Express!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
8. Debugging
- Debug with Node:
node inspect yourfile.js
- Using Chrome DevTools:
node --inspect yourfile.js
9. Commonly Used Modules
- Path:
const path = require('path'); console.log(path.join(__dirname, 'file.txt'));
- OS:
const os = require('os'); console.log(os.platform());
- HTTP:
const http = require('http');
10. Tips
- Use
nodemon
for auto-reloading during development:
npm install -g nodemon nodemon yourfile.js