Node js

Global varibels

  1. __filename -> full fill path
  2. __dirname -> parent folder full path
  3. require -> global function used to import modules
  4. module -> info about current module
  5. process -> info about current the host device

Modules

1. make your modual

every file is a modual

  1. export somthing from file
const somthing = 'somthing'; module.exports = somthing;
  1. import somthing from another file
const somthing = require('./filepath');

Full Example

// at -> file2.js module.exports = () => { for (let i = 0; i < 1000; i++) { console.log(`Hello number ${i}`); } } ------------------------------------------------- // at -> index.js const loop = require("./file2"); loop();

NOTE: when you require a file all code in file will run
EXAMPLE

// at -> file2.js console.log("hello world"); module.exports = "test" ------------------------------------------------- // at -> index.js const test = require("./file2");

Terminal

node index.js hello world

2. built in moduals

  1. OS MODUAL
const OS = require('os'); // info about user const user = OS.userInfo() console.log(user); // system up time in secound console.log(`System up time : ${OS.uptime()}`);
  1. PATH MODUAL
const path = require('path') console.log(path.sep); // out -> \ console.log(path.join("hello" , "world" , "this" , "is" , "a" , "test")); // out -> hello\world\this\is\a\test console.log(path.basename('hello/world/this/is/a/test/hello.js')); // out -> hello.js
  1. FS MODUAL
  • sync functions : stop all tasks until finish this task
const { writeFileSync, readFileSync } = require("fs");

Example

const { writeFileSync, readFileSync } = require("fs");
const os = require("os");

// {flag : a} is optional but it tell the node does not override the file just append the new text
writeFileSync("./firstFile.txt", ``)
for (let i = 0; i <= 5000; i++) {
    writeFileSync("./firstFile.txt", `${i}) lorem lorem lorem lorem ${os.EOL}`, { flag: "a" })
}

// second parameter is optional
const text = readFileSync("./firstFile.txt", 'utf-8');
text.split(os.EOL).forEach(el => {
    console.log(el);
});
  • async functions : do another task will this task are done then when this task
const { readFile, writeFile } = require('fs'); readFile('filePath','utf-8', /*call back function*/(error, result) => { console.log(result);})

Full Example

const { readFile, writeFile } = require('fs');
writeFile('./firstFile.txt', " lorem", { flag: "a" }, erorr => {
    if (erorr) {
        console.error(erorr);
    }

})

readFile('./firstFile.txt', 'utf-8', (error, result) => {
    if (!error) {
        console.log(result);
    }
})
  1. http
    createServer: this method return a server object
    FULL EXAMPLE
const http = require('http');

const server = http.createServer();
server.on('request', (request, response) => {
    response.writeHead(200, 'OK', {
        'content-type': 'text/html'
    });
    response.write(`<h1>page : ${request.url.replace('/' , "")}</h1>`);
    response.end()
})

server.listen(5000)

Create package.json file

npm init -y

Dependencies

is a packages that built by another programers and they are published it in npm store and you can use it in your project

How to install dependencies package ?

npm i axios

Devdependencies

is a dependencies that you just need it in development step (you don't need it in production) like nodemon package.
How to install devdependencies package ?

npm i <package name> (-D or --save-dev)

Example

npm i nodemon -D

Note : nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application.

Scripts

"scripts": { "start": "nodemon index.js" }
npm run start

This will run 'nodemon index.js'

uninstall package

npm uninstall packageName

convert any async function into Promise

const util = require('util'); const { readFile, writeFile } = require('fs'); const readFilePromise = util.promisify(readFile); const writeFilePromise = util.promisify(writeFile); const readFileByPath = async (path) => { const res = await readFilePromise(path, 'utf-8') console.log(res); return res; } const writeFileToPath = async (path, text, KeepOld = false) => { if (KeepOld) { const res = await writeFilePromise(path, text, { flag: "a" }); return res; } else { const res = await writeFilePromise(path, text); return res; } } writeFileToPath("./helloWorld.txt", "lorem lorem lorem lorem ", true); readFileByPath("./helloWorld.txt")

OR YOU CAN GET READ AND WRITE AS PROMISES

const { readFile, writeFile } = require('fs').promises;

EVENTS

const Event = require('events'); const myEvent = new Event(); myEvent.on('first_event', () => { console.log("Hello World"); }) myEvent.emit('first_event')

Send data with the event

const Event = require('events'); const myEvent = new Event(); myEvent.on('first-event', (payload) => { console.log(`Hello ${payload.name}`); console.log(`Your age :${payload.age}`); }) myEvent.emit('first-event' , { name:'abd', age:15 })

Server use Event

const http = require('http'); const server = http.createServer(); server.on('request', (request, response) => { = response.end(`page : ${request.url}`) }) server.listen(5000)
// :todo createFileStream