# 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** ```jsx= const somthing = 'somthing'; module.exports = somthing; ``` 2. **import somthing from another file** ```jsx= const somthing = require('./filepath'); ``` **Full Example** ```jsx= // 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 ```jsx= // at -> file2.js console.log("hello world"); module.exports = "test" ------------------------------------------------- // at -> index.js const test = require("./file2"); ``` **Terminal** ```terminal= node index.js hello world ``` #### 2. built in moduals 1. OS MODUAL ```jsx= 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()}`); ``` 2. PATH MODUAL ```jsx= 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 ``` 3. FS MODUAL - **sync functions :** stop all tasks until finish this task ```jsx const { writeFileSync, readFileSync } = require("fs"); ``` **Example** ```jsx 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 ```jsx= const { readFile, writeFile } = require('fs'); readFile('filePath','utf-8', /*call back function*/(error, result) => { console.log(result);}) ``` **Full Example** ```jsx 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); } }) ``` 4. http **createServer:** this method return a server object **FULL EXAMPLE** ```jsx 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 ```js= 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 ?** ```js= 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 ?** ```js= npm i <package name> (-D or --save-dev) ``` **Example** ```jsx= npm i nodemon -D ``` **Note :** nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application. ### Scripts ```jsx= "scripts": { "start": "nodemon index.js" } ``` ```jsx= npm run start ``` **This will run 'nodemon index.js'** ### uninstall package ```jsx= npm uninstall packageName ``` ### convert any async function into Promise ```jsx= 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** ```jsx= const { readFile, writeFile } = require('fs').promises; ``` ### EVENTS ```jsx= 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 ```jsx= 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 ```jsx= const http = require('http'); const server = http.createServer(); server.on('request', (request, response) => { = response.end(`page : ${request.url}`) }) server.listen(5000) ``` ```jsx // :todo createFileStream ```