JavaScript Node.js Basics

Introduction

Node.js lets you run JavaScript outside the browser — on servers, desktops, CLIs, APIs, bots, and automation scripts. It is event-driven, fast, and perfect for building lightweight services.

1. Installing Node

Download from nodejs.org or use:

# Windows
winget install OpenJS.NodeJS

# Linux
sudo apt install nodejs npm
    

2. Check Version

node -v
npm -v
    

3. Running a JS File

console.log("Hello Node");

# Run
node app.js
    

4. Using Modules (CommonJS)

// math.js
function add(a,b){ return a+b; }
module.exports = { add };

// main.js
const math = require("./math");
console.log(math.add(5,3));
    

5. ES Modules

// package.json
{ "type": "module" }

// math.js
export function add(a,b){ return a+b; }

// main.js
import { add } from "./math.js";
console.log(add(2,4));
    

6. Reading & Writing Files

const fs = require("fs");

fs.writeFileSync("test.txt", "Hello");
const content = fs.readFileSync("test.txt", "utf8");
console.log(content);
    

7. Creating a Simple Server

const http = require("http");

const server = http.createServer((req,res)=>{
  res.end("Hello from Node server");
});

server.listen(3000);
console.log("Running on http://localhost:3000");
    

8. Using npm

npm init -y
npm install express
    

9. Express Basics

import express from "express";

const app = express();

app.get("/", (req,res)=>{
  res.send("Welcome!");
});

app.listen(3000);
    

10. JSON APIs

app.get("/api/user", (req,res)=>{
  res.json({ name:"Kaloyan", age:12 });
});
    

11. Environment Variables (.env)

# .env
TOKEN=12345

# index.js
import dotenv from "dotenv";
dotenv.config();

console.log(process.env.TOKEN);
    

12. File System Automation

fs.readdirSync(".").forEach(f => console.log(f));
    

13. Running Child Processes

import { exec } from "child_process";

exec("ping 8.8.8.8", (err, out) => {
  console.log(out);
});
    

14. Node for Bots (Telegram Example)

import TelegramBot from "node-telegram-bot-api";

const bot = new TelegramBot("TOKEN", { polling:true });

bot.onText(/\/start/, msg =>{
  bot.sendMessage(msg.chat.id, "Bot ready!");
});
    

15. Summary