?? Node.js Quick Reference
Variables
const name = 'Tech';
let count = 10;
var old = 5;
??? Console Output
console.log('Hello');
console.error('Error!');
console.warn('Warning!');
?? Functions
function greet(name) {
return 'Hello ' + name;
}
const add = (a, b) => a + b;
?? Arrays
const arr = [1, 2, 3];
arr.push(4);
arr.pop();
arr.map(x => x * 2);
?? Objects
const user = {
name: 'John',
age: 25,
greet() { return `Hi ${this.name}`; }
};
Modules
const fs = require('fs');
const path = require('path');
const http = require('http');
?? HTTP Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello World');
});
server.listen(3000);
? Express.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello');
});
app.listen(3000);
? Async/Await
async function readData() {
try {
const data = await fs.readFile('file.txt');
console.log(data);
} catch(err) {
console.error(err);
}
}
? Database (MongoDB)
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');
const User = mongoose.model('User', {
name: String,
email: String
});