diff --git a/src/docs/Basics/Email.md b/src/docs/Basics/Email.md index 4a079da..685e9ad 100644 --- a/src/docs/Basics/Email.md +++ b/src/docs/Basics/Email.md @@ -6,4 +6,81 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +In this tutorial, we'll explore how to use the Nodemailer module to send emails from your Node.js server. + +## The Nodemailer Module + +The Nodemailer module simplifies the process of sending emails from your computer. You can easily download and install the Nodemailer module using npm: + +```bash +npm install nodemailer +``` + +After installing the Nodemailer module, you can include it in any application: + +```javascript +var nodemailer = require('nodemailer'); +``` + +## Sending an Email + +Now that you've installed the Nodemailer module, you're ready to send emails from your server. Let's walk through an example of sending an email using your Gmail account: + +```javascript +var nodemailer = require('nodemailer'); + +var transporter = nodemailer.createTransport({ + service: 'gmail', + auth: { + user: 'youremail@gmail.com', + pass: 'yourpassword' + } +}); + +var mailOptions = { + from: 'youremail@gmail.com', + to: 'myfriend@yahoo.com', + subject: 'Sending Email using Node.js', + text: 'That was easy!' +}; + +transporter.sendMail(mailOptions, function(error, info){ + if (error) { + console.log(error); + } else { + console.log('Email sent: ' + info.response); + } +}); +``` + +And that's it! Your server is now capable of sending emails. + +## Multiple Receivers + +To send an email to multiple receivers, simply add them to the `to` property of the `mailOptions` object, separated by commas: + +```javascript +var mailOptions = { + from: 'youremail@gmail.com', + to: 'myfriend@yahoo.com, myotherfriend@yahoo.com', + subject: 'Sending Email using Node.js', + text: 'That was easy!' +} +``` + +## Send HTML + +If you want to send HTML-formatted text in your email, use the `html` property instead of the `text` property: + +```javascript +var mailOptions = { + from: 'youremail@gmail.com', + to: 'myfriend@yahoo.com', + subject: 'Sending Email using Node.js', + html: '

Welcome

That was easy!

' +} +``` + +That's all you need to know to start sending emails from your Node.js server using the Nodemailer module. \ No newline at end of file diff --git a/src/docs/Basics/Events.md b/src/docs/Basics/Events.md index ac77028..fc7189c 100644 --- a/src/docs/Basics/Events.md +++ b/src/docs/Basics/Events.md @@ -6,4 +6,51 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +In this tutorial, we'll explore how Node.js is ideal for building event-driven applications. + +## Events in Node.js + +Node.js is well-suited for event-driven applications, where every action on a computer is treated as an event. For example, when a connection is made or a file is opened, these are considered events. + +Objects in Node.js can fire events, such as the `readStream` object which fires events when opening and closing a file. Let's see an example: + +```javascript +var fs = require('fs'); +var rs = fs.createReadStream('./demofile.txt'); +rs.on('open', function () { + console.log('The file is open'); +}); +``` + +## Events Module + +Node.js provides a built-in module called "Events" that allows you to create, fire, and listen for your own events. + +To include the built-in Events module, use the `require()` method. Additionally, all event properties and methods are instances of an EventEmitter object. To access these properties and methods, create an EventEmitter object: + +```javascript +var events = require('events'); +var eventEmitter = new events.EventEmitter(); +``` + +## The EventEmitter Object + +You can assign event handlers to your own events using the EventEmitter object. In the following example, we've created a function that will be executed when a "scream" event is fired. To fire an event, use the `emit()` method. + +```javascript +var events = require('events'); +var eventEmitter = new events.EventEmitter(); + +// Create an event handler: +var myEventHandler = function () { + console.log('I hear a scream!'); +} + +// Assign the event handler to an event: +eventEmitter.on('scream', myEventHandler); + +// Fire the 'scream' event: +eventEmitter.emit('scream'); +``` \ No newline at end of file diff --git a/src/docs/Basics/File System.md b/src/docs/Basics/File System.md index a16d98d..7f0fb7d 100644 --- a/src/docs/Basics/File System.md +++ b/src/docs/Basics/File System.md @@ -6,4 +6,108 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +In this tutorial, we'll explore how to work with the file system on your computer using Node.js. + +## Node.js as a File Server + +The Node.js file system module allows you to perform various operations on files, such as reading, creating, updating, deleting, and renaming files. To include the File System module, use the `require()` method: + +```javascript +var fs = require('fs'); +``` + +## Read Files + +The `fs.readFile()` method is used to read files on your computer. Let's see an example of reading an HTML file: + +```javascript +var http = require('http'); +var fs = require('fs'); + +http.createServer(function (req, res) { + fs.readFile('demofile1.html', function(err, data) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write(data); + return res.end(); + }); +}).listen(8080); +``` + +## Create Files + +The File System module provides methods for creating new files, such as `fs.appendFile()`, `fs.open()`, and `fs.writeFile()`. Let's see examples of creating new files: + +```javascript +var fs = require('fs'); + +fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { + if (err) throw err; + console.log('Saved!'); +}); +``` + +```javascript +var fs = require('fs'); + +fs.open('mynewfile2.txt', 'w', function (err, file) { + if (err) throw err; + console.log('Saved!'); +}); +``` + +```javascript +var fs = require('fs'); + +fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) { + if (err) throw err; + console.log('Saved!'); +}); +``` + +## Update and Delete Files + +The File System module also provides methods for updating and deleting files, such as `fs.appendFile()`, `fs.writeFile()`, and `fs.unlink()`. Let's see examples of updating and deleting files: + +```javascript +var fs = require('fs'); + +fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) { + if (err) throw err; + console.log('Updated!'); +}); +``` + +```javascript +var fs = require('fs'); + +fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { + if (err) throw err; + console.log('Replaced!'); +}); +``` + +```javascript +var fs = require('fs'); + +fs.unlink('mynewfile2.txt', function (err) { + if (err) throw err; + console.log('File deleted!'); +}); +``` + +## Rename Files + +To rename a file, use the `fs.rename()` method: + +```javascript +var fs = require('fs'); + +fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) { + if (err) throw err; + console.log('File Renamed!'); +}); +``` + +You can perform various file operations easily using these methods 📁 \ No newline at end of file diff --git a/src/docs/Basics/HTTP Modules.md b/src/docs/Basics/HTTP Modules.md index be55d02..56dc031 100644 --- a/src/docs/Basics/HTTP Modules.md +++ b/src/docs/Basics/HTTP Modules.md @@ -6,4 +6,76 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +Let's explore how Node.js utilizes the built-in HTTP module to transfer data over the Hyper Text Transfer Protocol (HTTP). + +## The Built-in HTTP Module + +Node.js provides a built-in module called HTTP, which allows you to create HTTP servers and handle HTTP requests and responses. To include the HTTP module, use the `require()` method: + +```javascript +var http = require('http'); +``` + +## Node.js as a Web Server + +With the HTTP module, Node.js can act as a web server by creating an HTTP server that listens to server ports and responds to client requests. Use the `createServer()` method to create an HTTP server: + +```javascript +var http = require('http'); + +// Create a server object: +http.createServer(function (req, res) { + res.write('Hello World!'); // Write a response to the client + res.end(); // End the response +}).listen(8080); // The server object listens on port 8080 +``` + +The function passed into the `http.createServer()` method will be executed when someone tries to access the computer on port 8080. + +## Add an HTTP Header + +To display the response from the HTTP server as HTML, include an HTTP header with the correct content type: + +```javascript +var http = require('http'); + +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write('Hello World!'); + res.end(); +}).listen(8080); +``` + +The first argument of the `res.writeHead()` method is the status code, where 200 means that all is OK, and the second argument is an object containing the response headers. + +## Read the Query String + +The `req` argument of the function passed into `http.createServer()` represents the request from the client as an object (`http.IncomingMessage` object). It has a property called "url" which holds the part of the URL that comes after the domain name: + +```javascript +var http = require('http'); + +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write(req.url); + res.end(); +}).listen(8080); +``` + +## Split the Query String + +You can easily split the query string into readable parts using the built-in URL module: + +```javascript +var http = require('http'); +var url = require('url'); + +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + var q = url.parse(req.url, true).query; + var txt = q.year + " " + q.month; + res.end(txt); +}).listen(8080); +``` \ No newline at end of file diff --git a/src/docs/Basics/Modules.md b/src/docs/Basics/Modules.md index 8091123..fdecb2b 100644 --- a/src/docs/Basics/Modules.md +++ b/src/docs/Basics/Modules.md @@ -6,4 +6,99 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +In this tutorial, we'll explore how modules work in Node.js, including built-in modules and how to create and include your own modules. + +## What is a Module in Node.js? + +In Node.js, modules are similar to JavaScript libraries. They consist of a set of functions or pieces of code that you can include in your application. + +## Built-in Modules + +Node.js comes with a rich set of built-in modules that you can use right out of the box, without any additional installation. These modules provide essential functionalities for various tasks. + +Here's a list of some built-in modules available in Node.js version 6.10.3: + +| Module | Description | +|----------------|-------------------------------------------------------------| +| assert | Provides a set of assertion tests | +| buffer | Handles binary data | +| child_process | Runs a child process | +| cluster | Splits a single Node process into multiple processes | +| crypto | Handles OpenSSL cryptographic functions | +| dgram | Provides implementation of UDP datagram sockets | +| dns | Performs DNS lookups and name resolution functions | +| domain | ***Deprecated.*** Handles unhandled errors | +| events | Handles events | +| fs | Handles the file system | +| http | Makes Node.js act as an HTTP server | +| https | Makes Node.js act as an HTTPS server | +| net | Creates servers and clients | +| os | Provides information about the operating system | +| path | Handles file paths | +| punycode | ***Deprecated.*** A character encoding scheme | +| querystring | Handles URL query strings | +| readline | Handles readable streams one line at a time | +| stream | Handles streaming data | +| string_decoder | Decodes buffer objects into strings | +| timers | Executes a function after a given number of milliseconds | +| tls | Implements TLS and SSL protocols | +| tty | Provides classes used by a text terminal | +| url | Parses URL strings | +| util | Accesses utility functions | +| v8 | Accesses information about V8 (the JavaScript engine) | +| vm | Compiles JavaScript code in a virtual machine | +| zlib | Compresses or decompresses files | + +To include a built-in module, use the `require()` function with the name of the module: + +```javascript +var http = require('http'); +``` + +Now your application has access to the HTTP module, allowing you to create a server like this: + +```javascript +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end('Hello World!'); +}).listen(8080); +``` + +## Create Your Own Modules + +You can also create your own modules and easily include them in your applications. Let's create an example module that returns the current date and time: + +```javascript +// myfirstmodule.js + +exports.myDateTime = function () { + return Date(); +}; +``` + +Use the `exports` keyword to make properties and methods available outside the module file. + +## Include Your Own Module + +Now that you've created your own module, you can include and use it in any of your Node.js files. Here's how to use the "myfirstmodule" module in a Node.js file: + +```javascript +var http = require('http'); +var dt = require('./myfirstmodule'); + +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write("The date and time are currently: " + dt.myDateTime()); + res.end(); +}).listen(8080); +``` + +Notice that we use `./` to locate the module, indicating that the module is located in the same folder as the Node.js file. + +Save the code above in a file called "demo_module.js", and initiate the file: + +```bash +C:\Users\Your Name>node demo_module.js +``` diff --git a/src/docs/Basics/NPM.md b/src/docs/Basics/NPM.md index 331a1f5..3f9d75a 100644 --- a/src/docs/Basics/NPM.md +++ b/src/docs/Basics/NPM.md @@ -6,4 +6,51 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +NPM, short for Node Package Manager, is a package manager designed specifically for Node.js packages or modules. It serves as a central repository where you can find and download thousands of free packages to use in your Node.js projects. You can explore available packages at [www.npmjs.com](https://www.npmjs.com/). + +The NPM program comes pre-installed on your computer when you install Node.js, making it readily available for use without any additional setup. + +## What is a Package? + +In the context of Node.js, a package contains all the files necessary for a module. Modules are JavaScript libraries that you can include and utilize within your projects. + +## Download a Package + +Downloading a package using NPM is straightforward. Simply open your command line interface and instruct NPM to download the desired package. For example, to download a package named "upper-case", you would use the following command: + +```bash +C:\Users\Your Name>npm install upper-case +``` + +This command will download and install the "upper-case" package onto your system. NPM creates a folder named "node_modules" where the downloaded package is placed. Any future packages you install will also be stored in this folder. + +## Using a Package + +Once the package is installed, you can easily include it in your Node.js files just like any other module. For instance, to use the "upper-case" package, you would include it in your file as follows: + +```javascript +var uc = require('upper-case'); +``` + +Now, you can utilize the functionalities provided by the "upper-case" package in your code. Here's an example of creating a Node.js file that converts the output "Hello World!" into uppercase letters using the "upper-case" package: + +```javascript +// demo_uppercase.js + +var http = require('http'); +var uc = require('upper-case'); + +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write(uc.upperCase("Hello World!")); + res.end(); +}).listen(8080); +``` + +Save the above code in a file named "demo_uppercase.js" and execute it in your command line interface: + +```bash +C:\Users\Your Name>node demo_uppercase.js +``` diff --git a/src/docs/Basics/URL Module.md b/src/docs/Basics/URL Module.md index 76b4d1e..b9147bf 100644 --- a/src/docs/Basics/URL Module.md +++ b/src/docs/Basics/URL Module.md @@ -6,4 +6,104 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +In this tutorial, we'll explore how Node.js uses the built-in URL module to parse web addresses. + +## The Built-in URL Module + +The URL module in Node.js helps split a web address into readable parts. To include the URL module, use the `require()` method: + +```javascript +var url = require('url'); +``` + +You can parse a web address using the `url.parse()` method, which returns a URL object with each part of the address as properties: + +```javascript +var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; +var q = url.parse(adr, true); + +console.log(q.host); // returns 'localhost:8080' +console.log(q.pathname); // returns '/default.htm' +console.log(q.search); // returns '?year=2017&month=february' + +var qdata = q.query; // returns an object: { year: 2017, month: 'february' } +console.log(qdata.month); // returns 'february' +``` + +### Node.js File Server + +Now, let's combine our knowledge of parsing query strings with serving files using Node.js as a file server. + +#### Step 1: Create HTML Files + +Create two HTML files, `summer.html` and `winter.html`, and save them in the same folder as your Node.js files. + +##### summer.html + +```html + + + +

Summer

+

I love the sun!

+ + +``` + +##### winter.html + +```html + + + +

Winter

+

I love the snow!

+ + +``` + +#### Step 2: Create the File Server + +Now, create a Node.js file, `demo_fileserver.js`, that opens the requested file and returns its content to the client. If anything goes wrong, throw a 404 error: + +```javascript +var http = require('http'); +var url = require('url'); +var fs = require('fs'); + +http.createServer(function (req, res) { + var q = url.parse(req.url, true); + var filename = "." + q.pathname; + fs.readFile(filename, function(err, data) { + if (err) { + res.writeHead(404, {'Content-Type': 'text/html'}); + return res.end("404 Not Found"); + } + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write(data); + return res.end(); + }); +}).listen(8080); +``` + +Remember to initiate the file: + +```bash +C:\Users\Your Name>node demo_fileserver.js +``` + +If you have followed the same steps on your computer, you should see two different results when opening these two addresses: + + - [http://localhost:8080/summer.html](http://localhost:8080/summer.html) will display: + ```bash + Summer + I love the sun! + ``` + + - [http://localhost:8080/winter.html](http://localhost:8080/winter.html) will display: + ```bash + Winter + I love the snow! + ``` diff --git a/src/docs/Basics/Upload Files.md b/src/docs/Basics/Upload Files.md index 4ac50b8..2a2eacc 100644 --- a/src/docs/Basics/Upload Files.md +++ b/src/docs/Basics/Upload Files.md @@ -6,4 +6,75 @@ category: - Docs-Basics footer: false ---- \ No newline at end of file +--- + +In this tutorial, we'll explore how to upload files to your Node.js server using the Formidable module. + +## The Formidable Module + +The "Formidable" module is an excellent tool for handling file uploads in Node.js applications. To use Formidable, you can install it via NPM: + +```bash +C:\Users\Your Name>npm install formidable +``` + +Once installed, you can include Formidable in your application: + +```javascript +var formidable = require('formidable'); +``` + +### Upload Files + +Now, let's create a web page in Node.js that allows users to upload files to your server. + +#### Step 1: Create an Upload Form + +First, create a Node.js file that generates an HTML form with an upload field: + +```javascript +var http = require('http'); + +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write('
'); + res.write('
'); + res.write(''); + res.write('
'); + return res.end(); +}).listen(8080); +``` + +#### Step 2: Parse the Uploaded File + +To handle the uploaded file, include the Formidable module: + +```javascript +var formidable = require('formidable'); +``` + +Then, parse the uploaded file: + +```javascript +var form = new formidable.IncomingForm(); +form.parse(req, function (err, fields, files) { + res.write('File uploaded'); + res.end(); +}); +``` + +#### Step 3: Save the File + +Once the file is uploaded and parsed, it's placed in a temporary folder on your server. To move it to a permanent location, you can use the File System module: + +```javascript +var fs = require('fs'); + +var oldpath = files.filetoupload.path; +var newpath = 'C:/Users/Your Name/' + files.filetoupload.name; +fs.rename(oldpath, newpath, function (err) { + if (err) throw err; + res.write('File uploaded and moved!'); + res.end(); +}); +``` \ No newline at end of file