Sure, let's go through each concept with examples:
Nodemon Module Concept
Nodemon is a tool that helps develop Node.js based applications by automatically restarting the application when file changes are detected in the directory.
Installation:
npm install -g nodemon
Usage:
Instead of running your app with `node app.js`, you can run it with:
nodemon app.js
Nodemon will automatically restart your server whenever you make changes to your files.
URL Module
The URL module splits up a web address into readable parts.
Example:
const url = require('url');
const address = 'http://example.com:8080/default.htm?year=2023&month=july';
const parsedUrl = url.parse(address, true);
console.log(parsedUrl.host); // 'example.com:8080'
console.log(parsedUrl.pathname); // '/default.htm'
console.log(parsedUrl.search); // '?year=2023&month=july'
const queryData = parsedUrl.query;
console.log(queryData.year); // '2023'
console.log(queryData.month); // 'july'
Custom Module in Node.js
You can create your own modules in Node.js.
Example:
Create a file named `myModule.js`:
// myModule.js
exports.myFunction = function() {
console.log("Hello from my module!");
};
In your main file (`app.js`):
const myModule = require('./myModule');
myModule.myFunction(); // Outputs: Hello from my module!
Export Custom Module
You can export multiple items from a module.
Example:
// myModule.js
const myFunction = () => {
console.log("Hello from my module!");
};
const myVariable = "Exported Variable";
module.exports = {
myFunction,
myVariable
};
In your main file (`app.js`):
const myModule = require('./myModule');
myModule.myFunction(); // Outputs: Hello from my module!
console.log(myModule.myVariable); // Outputs: Exported Variable
Custom Events in Node.js
Using the `events` module, you can create and handle custom events.
Example:
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
// Create an event listener
eventEmitter.on('greet', () => {
console.log('Hello world!');
});
// Trigger the event
eventEmitter.emit('greet');
Nested Custom Events
You can emit events within event handlers.
Example:
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('firstEvent', () => {
console.log('First Event');
eventEmitter.emit('secondEvent');
});
eventEmitter.on('secondEvent', () => {
console.log('Second Event');
});
eventEmitter.emit('firstEvent');
Custom Event Module
You can create a module to handle custom events.
Example:
Create a file named `eventModule.js`:
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('sayHello', () => {
console.log('Hello from custom event module!');
});
module.exports = eventEmitter;
In your main file (`app.js`):
const eventModule = require('./eventModule');
eventModule.emit('sayHello'); // Outputs: Hello from custom event module!
FS Module
The FS (File System) module allows you to work with the file system on your computer.
Example:
const fs = require('fs');
File Read Examples:
1. Read Text File:
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
2. Read HTML File:
fs.readFile('example.html', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
3. Read JSON File:
fs.readFile('example.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const jsonData = JSON.parse(data);
console.log('JSON content:', jsonData);
});
Example Summary
Here’s a brief summary of all examples in a single Node.js project:
1. Install Nodemon:
npm install -g nodemon
2. Create `app.js`:
const http = require('http');
const fs = require('fs');
const url = require('url');
const eventEmitter = require('./eventModule');
const myModule = require('./myModule');
// URL Module Example
const address = 'http://example.com:8080/default.htm?year=2023&month=july';
const parsedUrl = url.parse(address, true);
console.log(parsedUrl.host);
console.log(parsedUrl.pathname);
console.log(parsedUrl.search);
console.log(parsedUrl.query.year);
console.log(parsedUrl.query.month);
// FS Module Example
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
// Custom Module Example
myModule.myFunction();
console.log(myModule.myVariable);
// Custom Event Module Example
eventEmitter.emit('sayHello');
// Creating a Server Example
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Hello World!');
res.end();
});
server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
3. Create `myModule.js`:
const myFunction = () => {
console.log("Hello from my module!");
};
const myVariable = "Exported Variable";
module.exports = {
myFunction,
myVariable
};
4. Create `eventModule.js`:
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('sayHello', () => {
console.log('Hello from custom event module!');
});
module.exports = eventEmitter;
5. Create `example.txt`:
This is a sample text file.
6. Run the app with Nodemon:
nodemon app.js
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
Custom.js
var msg="hello welcome to node js"; const fact=(num)=>{ let f=1; for(i=1;i<=num;i++) { f=f*i; } return f; } const ischeck=(n)=>{ if(n%2==0) { console.log("even number"); } else { console.log("odd number"); } } var emp={ id:10, nm:'sourav', dept:'science', loc:'kolkata' } module.exports={ mg:msg, factfun:fact, chk:ischeck, info:emp }
event1.js
const events=require('events'); const handle=new events.EventEmitter(); handle.on('square',(n)=>{ console.log("Square result : "+n*n); }) handle.emit('square',5);event2.jsconst event=require('events'); const handle=new event.EventEmitter(); handle.on('first',()=>{ console.log("first event is fired..!"); handle.emit('second'); }) handle.on('second',()=>{ console.log('second event is called'); handle.emit('third'); }) handle.on('third',()=>{ console.log('third event is called'); }) handle.emit('first');
evntmodule.js
const events=require('events'); const handle=new events.EventEmitter(); handle.on('iseven',(n)=>{ if(n%2==0) { console.log("even"); } else { console.log("odd") } }) handle.on('fact',(v)=>{ let f=1; for(i=1;i<=v;i++) { f=f*i; } console.log(f); }) handle.on('disp',(msg)=>{ console.log(msg); }) module.exports.evobj=handle;
package.json
{ "name": "satsunbatch", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "nodemon server.js" }, "author": "skundu", "license": "ISC", "dependencies": { "axios": "^1.7.2", "nodemon": "^3.1.4" } }
read.js
const fs=require('fs'); fs.readFile('./test2.json',(err,data)=>{ try{ if(err) throw err; let result=JSON.parse(data); console.log(result.city); } catch(err) { console.log(err); } })read2.jsconst fs=require('fs'); const http=require('http'); const port=4000; fs.readFile('./test3.html',(err,data)=>{ try { if(err) throw err; console.log('read is success'); let serv=http.createServer((req,res)=>{ res.writeHead(200,{'Content-Type': 'text/html'}); res.write(data); res.end(); }) serv.listen(port,()=>{ console.log(`server is running in port ${port}`); }) } catch(err) { console.log(err); } })server.jsconst http=require('http'); const port=4000; const server=http.createServer((req,res)=>{ res.writeHead(200,{'Content-Type': 'text/html'}); res.write(`<ul><li>hello express </li><li>hello php</li></ul>`); res.write('<h3>Thank You have a nice day!</h3>') res.write('<ol><li>hello welcome</li><li>thank you</li></ol>') res.end(); }) server.listen(port,()=>{ console.log(`server is running in the port ${port}`) })url.jsconst url=require('url'); var urlex='http://localhost:8080/default.html?year=2017&month=february'; console.log(url.parse(urlex));use.jsconst test=require('./custom'); console.log(test.mg); console.log(test.factfun(5)); test.chk(20); console.log(test.info);use2.jsconst evntmod=require('./evntmod'); evntmod.evobj.emit('iseven',10); evntmod.evobj.emit('fact',5); evntmod.evobj.emit('disp','thank you');
Comments
Post a Comment