404
Page not found
That’s a Four-Oh-Four.
diff --git a/.gitignore b/.gitignore index 4803e09..6a421d1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ node_modules/ docs/.vuepress/.cache/ docs/.vuepress/.temp/ -docs/.vuepress/dist/ +# docs/.vuepress/dist/ diff --git a/docs/.vuepress/dist/404.html b/docs/.vuepress/dist/404.html new file mode 100644 index 0000000..03d5b69 --- /dev/null +++ b/docs/.vuepress/dist/404.html @@ -0,0 +1,40 @@ + + +
+ + + + + + +In this tutorial, we'll explore how to use the Nodemailer module to send emails from your Node.js server.
The Nodemailer module simplifies the process of sending emails from your computer. You can easily download and install the Nodemailer module using npm:
npm install nodemailer
+
After installing the Nodemailer module, you can include it in any application:
var nodemailer = require('nodemailer');
+
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:
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.
To send an email to multiple receivers, simply add them to the to
property of the mailOptions
object, separated by commas:
var mailOptions = {
+ from: 'youremail@gmail.com',
+ to: 'myfriend@yahoo.com, myotherfriend@yahoo.com',
+ subject: 'Sending Email using Node.js',
+ text: 'That was easy!'
+}
+
If you want to send HTML-formatted text in your email, use the html
property instead of the text
property:
var mailOptions = {
+ from: 'youremail@gmail.com',
+ to: 'myfriend@yahoo.com',
+ subject: 'Sending Email using Node.js',
+ html: '<h1>Welcome</h1><p>That was easy!</p>'
+}
+
That's all you need to know to start sending emails from your Node.js server using the Nodemailer module.
`,17),p=[o];function l(i,r){return s(),a("div",null,p)}const u=n(t,[["render",l],["__file","Email.html.vue"]]),m=JSON.parse(`{"path":"/docs/Basics/Email.html","title":"Email","lang":"en-US","frontmatter":{"title":"Email","index":true,"icon":"envelope","category":["Docs-Basics"],"footer":false,"description":"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 s...","head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/docs/Basics/Email.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"Email"}],["meta",{"property":"og:description","content":"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 s..."}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-16T14:12:27.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-16T14:12:27.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"Email\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-16T14:12:27.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[{"level":2,"title":"The Nodemailer Module","slug":"the-nodemailer-module","link":"#the-nodemailer-module","children":[]},{"level":2,"title":"Sending an Email","slug":"sending-an-email","link":"#sending-an-email","children":[]},{"level":2,"title":"Multiple Receivers","slug":"multiple-receivers","link":"#multiple-receivers","children":[]},{"level":2,"title":"Send HTML","slug":"send-html","link":"#send-html","children":[]}],"git":{"createdTime":1713263632000,"updatedTime":1713276747000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":2}]},"readingTime":{"minutes":0.9,"words":269},"filePathRelative":"docs/Basics/Email.md","localizedDate":"April 16, 2024","autoDesc":true}`);export{u as comp,m as data}; diff --git a/docs/.vuepress/dist/assets/Events.html-Bwplr5d5.js b/docs/.vuepress/dist/assets/Events.html-Bwplr5d5.js new file mode 100644 index 0000000..9cf8adb --- /dev/null +++ b/docs/.vuepress/dist/assets/Events.html-Bwplr5d5.js @@ -0,0 +1,21 @@ +import{_ as n}from"./plugin-vue_export-helper-DlAUqK2U.js";import{o as e,c as s,a}from"./app-DxD832dz.js";const t={},o=a(`In this tutorial, we'll explore how Node.js is ideal for building event-driven applications.
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:
var fs = require('fs');
+var rs = fs.createReadStream('./demofile.txt');
+rs.on('open', function () {
+ console.log('The file is open');
+});
+
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:
var events = require('events');
+var eventEmitter = new events.EventEmitter();
+
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.
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');
+
In this tutorial, we'll explore how to work with the file system on your computer using Node.js.
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:
var fs = require('fs');
+
The fs.readFile()
method is used to read files on your computer. Let's see an example of reading an HTML file:
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);
+
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:
var fs = require('fs');
+
+fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
+ if (err) throw err;
+ console.log('Saved!');
+});
+
var fs = require('fs');
+
+fs.open('mynewfile2.txt', 'w', function (err, file) {
+ if (err) throw err;
+ console.log('Saved!');
+});
+
var fs = require('fs');
+
+fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
+ if (err) throw err;
+ console.log('Saved!');
+});
+
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:
var fs = require('fs');
+
+fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
+ if (err) throw err;
+ console.log('Updated!');
+});
+
var fs = require('fs');
+
+fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
+ if (err) throw err;
+ console.log('Replaced!');
+});
+
var fs = require('fs');
+
+fs.unlink('mynewfile2.txt', function (err) {
+ if (err) throw err;
+ console.log('File deleted!');
+});
+
To rename a file, use the fs.rename()
method:
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 📁
`,21),o=[p];function c(i,l){return s(),a("div",null,o)}const d=n(t,[["render",c],["__file","File System.html.vue"]]),k=JSON.parse(`{"path":"/docs/Basics/File%20System.html","title":"File System","lang":"en-US","frontmatter":{"title":"File System","index":true,"icon":"file","category":["Docs-Basics"],"footer":false,"description":"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 va...","head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/docs/Basics/File%20System.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"File System"}],["meta",{"property":"og:description","content":"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 va..."}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-16T14:12:27.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-16T14:12:27.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"File System\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-16T14:12:27.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[{"level":2,"title":"Node.js as a File Server","slug":"node-js-as-a-file-server","link":"#node-js-as-a-file-server","children":[]},{"level":2,"title":"Read Files","slug":"read-files","link":"#read-files","children":[]},{"level":2,"title":"Create Files","slug":"create-files","link":"#create-files","children":[]},{"level":2,"title":"Update and Delete Files","slug":"update-and-delete-files","link":"#update-and-delete-files","children":[]},{"level":2,"title":"Rename Files","slug":"rename-files","link":"#rename-files","children":[]}],"git":{"createdTime":1713263632000,"updatedTime":1713276747000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":2}]},"readingTime":{"minutes":1.08,"words":325},"filePathRelative":"docs/Basics/File System.md","localizedDate":"April 16, 2024","autoDesc":true}`);export{d as comp,k as data}; diff --git a/docs/.vuepress/dist/assets/Find.html-i8fnYBKQ.js b/docs/.vuepress/dist/assets/Find.html-i8fnYBKQ.js new file mode 100644 index 0000000..66a47a8 --- /dev/null +++ b/docs/.vuepress/dist/assets/Find.html-i8fnYBKQ.js @@ -0,0 +1 @@ +import{_ as e}from"./plugin-vue_export-helper-DlAUqK2U.js";import{o as t,c as o}from"./app-DxD832dz.js";const n={};function a(i,r){return t(),o("div")}const m=e(n,[["render",a],["__file","Find.html.vue"]]),d=JSON.parse('{"path":"/docs/MongoDB/Find.html","title":"Find","lang":"en-US","frontmatter":{"title":"Find","index":true,"icon":"magnifying-glass","category":["Docs-MongoDB"],"footer":false,"head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/docs/MongoDB/Find.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"Find"}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-16T14:13:30.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-16T14:13:30.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"Find\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-16T14:13:30.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[],"git":{"createdTime":1713276810000,"updatedTime":1713276810000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":1}]},"readingTime":{"minutes":0.04,"words":12},"filePathRelative":"docs/MongoDB/Find.md","localizedDate":"April 16, 2024"}');export{m as comp,d as data}; diff --git a/docs/.vuepress/dist/assets/Flowing_LED.html-yxxD0ouy.js b/docs/.vuepress/dist/assets/Flowing_LED.html-yxxD0ouy.js new file mode 100644 index 0000000..802eaf5 --- /dev/null +++ b/docs/.vuepress/dist/assets/Flowing_LED.html-yxxD0ouy.js @@ -0,0 +1 @@ +import{_ as e}from"./plugin-vue_export-helper-DlAUqK2U.js";import{o as t,c as o}from"./app-DxD832dz.js";const r={};function a(i,n){return t(),o("div")}const l=e(r,[["render",a],["__file","Flowing_LED.html.vue"]]),m=JSON.parse('{"path":"/docs/RaspberryPi/Flowing_LED.html","title":"Flowing LED","lang":"en-US","frontmatter":{"title":"Flowing LED","index":true,"icon":"water","category":["Docs-Raspberry Pi"],"footer":false,"head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/docs/RaspberryPi/Flowing_LED.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"Flowing LED"}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-16T14:13:01.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-16T14:13:01.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"Flowing LED\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-16T14:13:01.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[],"git":{"createdTime":1713276781000,"updatedTime":1713276781000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":1}]},"readingTime":{"minutes":0.04,"words":13},"filePathRelative":"docs/RaspberryPi/Flowing_LED.md","localizedDate":"April 16, 2024"}');export{l as comp,m as data}; diff --git a/docs/.vuepress/dist/assets/GPIO_Introduction.html-D-NPgKme.js b/docs/.vuepress/dist/assets/GPIO_Introduction.html-D-NPgKme.js new file mode 100644 index 0000000..20ad749 --- /dev/null +++ b/docs/.vuepress/dist/assets/GPIO_Introduction.html-D-NPgKme.js @@ -0,0 +1 @@ +import{_ as t}from"./plugin-vue_export-helper-DlAUqK2U.js";import{o as e,c as o}from"./app-DxD832dz.js";const r={};function n(a,i){return e(),o("div")}const m=t(r,[["render",n],["__file","GPIO_Introduction.html.vue"]]),d=JSON.parse('{"path":"/docs/RaspberryPi/GPIO_Introduction.html","title":"GPIO Introduction","lang":"en-US","frontmatter":{"title":"GPIO Introduction","index":true,"icon":"plug","category":["Docs-Raspberry Pi"],"footer":false,"head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/docs/RaspberryPi/GPIO_Introduction.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"GPIO Introduction"}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-16T14:13:01.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-16T14:13:01.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"GPIO Introduction\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-16T14:13:01.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[],"git":{"createdTime":1713276781000,"updatedTime":1713276781000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":1}]},"readingTime":{"minutes":0.04,"words":13},"filePathRelative":"docs/RaspberryPi/GPIO_Introduction.md","localizedDate":"April 16, 2024"}');export{m as comp,d as data}; diff --git a/docs/.vuepress/dist/assets/HTTP Modules.html-kJ4VRSIz.js b/docs/.vuepress/dist/assets/HTTP Modules.html-kJ4VRSIz.js new file mode 100644 index 0000000..d3ad2de --- /dev/null +++ b/docs/.vuepress/dist/assets/HTTP Modules.html-kJ4VRSIz.js @@ -0,0 +1,32 @@ +import{_ as n}from"./plugin-vue_export-helper-DlAUqK2U.js";import{o as s,c as a,a as t}from"./app-DxD832dz.js";const e={},p=t(`Let's explore how Node.js utilizes the built-in HTTP module to transfer data over the Hyper Text Transfer Protocol (HTTP).
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:
var http = require('http');
+
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:
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.
To display the response from the HTTP server as HTML, include an HTTP header with the correct content type:
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.
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:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.write(req.url);
+ res.end();
+}).listen(8080);
+
You can easily split the query string into readable parts using the built-in URL module:
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);
+
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.
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.
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:
var http = require('http');
+
Now your application has access to the HTTP module, allowing you to create a server like this:
http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.end('Hello World!');
+}).listen(8080);
+
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:
// myfirstmodule.js
+
+exports.myDateTime = function () {
+ return Date();
+};
+
Use the exports
keyword to make properties and methods available outside the module file.
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:
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:
C:\\Users\\Your Name>node demo_module.js
+
The NPM program comes pre-installed on your computer when you install Node.js, making it readily available for use without any additional setup.
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.
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:
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.
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:
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:
// 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:
C:\\Users\\Your Name>node demo_uppercase.js
+
In this tutorial, we'll explore how Node.js uses the built-in URL module to parse web addresses.
The URL module in Node.js helps split a web address into readable parts. To include the URL module, use the require()
method:
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:
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'
+
Now, let's combine our knowledge of parsing query strings with serving files using Node.js as a file server.
Create two HTML files, summer.html
and winter.html
, and save them in the same folder as your Node.js files.
<!DOCTYPE html>
+<html>
+<body>
+<h1>Summer</h1>
+<p>I love the sun!</p>
+</body>
+</html>
+
<!DOCTYPE html>
+<html>
+<body>
+<h1>Winter</h1>
+<p>I love the snow!</p>
+</body>
+</html>
+
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:
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:
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:
`,20),r={href:"http://localhost:8080/summer.html",target:"_blank",rel:"noopener noreferrer"},d=a(`Summer
+I love the sun!
+
Winter
+I love the snow!
+
In this tutorial, we'll explore how to upload files to your Node.js server using 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:
C:\\Users\\Your Name>npm install formidable
+
Once installed, you can include Formidable in your application:
var formidable = require('formidable');
+
Now, let's create a web page in Node.js that allows users to upload files to your server.
First, create a Node.js file that generates an HTML form with an upload field:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
+ res.write('<input type="file" name="filetoupload"><br>');
+ res.write('<input type="submit">');
+ res.write('</form>');
+ return res.end();
+}).listen(8080);
+
To handle the uploaded file, include the Formidable module:
var formidable = require('formidable');
+
Then, parse the uploaded file:
var form = new formidable.IncomingForm();
+form.parse(req, function (err, fields, files) {
+ res.write('File uploaded');
+ res.end();
+});
+
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:
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();
+});
+
Welcome to the Node.js Documentation! In this comprehensive resource, you'll find detailed explanations of various Node.js concepts and functionalities. Let's explore the different sections together.
In the Basics section, you'll find essential topics that form the foundation of Node.js development. Here are some of the key topics covered:
In the MongoDB section, you'll delve into MongoDB integration with Node.js. Topics include:
In the MySQL section, you'll find in-depth information about using MySQL with Node.js. Whether you're a beginner or an experienced developer, you'll find valuable insights into working with MySQL databases. Some of the topics covered include:
In the Raspberry Pi section, you'll discover Node.js applications on Raspberry Pi. Topics include:
Get ready to level up your Node.js skills with our comprehensive documentation! 🚀
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/plain'});
+ res.end('Hello World!');
+}).listen(8080);
+
There are also some types of examples that you'll need to run via the command line. These examples will look like this:
console.log('This example is different!');
+console.log('The result is displayed in the Command Line Interface');
+
Once the download is complete, run the installer and follow the on-screen instructions. The installer will guide you through the installation process, including selecting the installation directory and any additional options you may want to configure.
After the installation is complete, you can verify that Node.js and npm (Node Package Manager) are installed correctly by opening a terminal or command prompt and typing the following commands:
node -v
+npm -v
+
These commands will display the versions of Node.js and npm installed on your system. If you see version numbers displayed, congratulations! You've successfully installed Node.js.
It's a good idea to keep npm up to date. You can do this by running the following command:
npm install npm@latest -g
+
This will update npm to the latest version available.
That's it! You've now installed Node.js on your system. You're ready to write your first Node.js program.
`,11),f={class:"hint-container note"},v=e("p",{class:"hint-container-title"},"Note",-1),_={href:"https://github.com/nodejs/node/issues/",target:"_blank",rel:"noopener noreferrer"};function b(w,k){const n=s("ExternalLinkIcon");return i(),l("div",null,[p,e("p",null,[t("There are several way to install Node.js, including using a "),e("a",c,[t("package manager"),a(n)]),t(", downloading "),e("a",h,[t("prebuilt binaries"),a(n)]),t(", or "),e("a",u,[t("building from source"),a(n)]),t(". In this guide, we'll cover the most common method of installing Node.js using the official installer.")]),m,e("p",null,[t("Visit "),e("a",g,[t("nodejs.org"),a(n)]),t(" and download the appropriate installer for your operating system (Windows, macOS, or Linux).")]),y,e("div",f,[v,e("p",null,[t("If you ran into any issues during the installation process, feel free to report them on the "),e("a",_,[t("Node.js GitHub repository"),a(n)])])])])}const I=o(d,[["render",b],["__file","installation.html.vue"]]),x=JSON.parse(`{"path":"/get-started/installation.html","title":"Installation guide","lang":"en-US","frontmatter":{"title":"Installation guide","index":true,"icon":"screwdriver-wrench","category":["Guides"],"footer":false,"description":"In this guide, we'll walk you through the process of installing Node.js on your system so you can start building awesome applications. There are several way to install Node.js, ...","head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/get-started/installation.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"Installation guide"}],["meta",{"property":"og:description","content":"In this guide, we'll walk you through the process of installing Node.js on your system so you can start building awesome applications. There are several way to install Node.js, ..."}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-15T20:12:13.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-15T20:12:13.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"Installation guide\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-15T20:12:13.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[{"level":3,"title":"Download Node.js","slug":"download-node-js","link":"#download-node-js","children":[]},{"level":3,"title":"Run the Installer","slug":"run-the-installer","link":"#run-the-installer","children":[]},{"level":3,"title":"Verify Installation","slug":"verify-installation","link":"#verify-installation","children":[]},{"level":3,"title":"Update npm (Optional)","slug":"update-npm-optional","link":"#update-npm-optional","children":[]}],"git":{"createdTime":1713203996000,"updatedTime":1713211933000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":2}]},"readingTime":{"minutes":0.96,"words":287},"filePathRelative":"get-started/installation.md","localizedDate":"April 15, 2024","autoDesc":true}`);export{I as comp,x as data}; diff --git a/docs/.vuepress/dist/assets/photoswipe.esm-SzV8tJDW.js b/docs/.vuepress/dist/assets/photoswipe.esm-SzV8tJDW.js new file mode 100644 index 0000000..4048314 --- /dev/null +++ b/docs/.vuepress/dist/assets/photoswipe.esm-SzV8tJDW.js @@ -0,0 +1,4 @@ +/*! + * PhotoSwipe 5.4.3 - https://photoswipe.com + * (c) 2023 Dmytro Semenov + */function f(r,t,i){const e=document.createElement(t);return r&&(e.className=r),i&&i.appendChild(e),e}function p(r,t){return r.x=t.x,r.y=t.y,t.id!==void 0&&(r.id=t.id),r}function M(r){r.x=Math.round(r.x),r.y=Math.round(r.y)}function A(r,t){const i=Math.abs(r.x-t.x),e=Math.abs(r.y-t.y);return Math.sqrt(i*i+e*e)}function x(r,t){return r.x===t.x&&r.y===t.y}function I(r,t,i){return Math.min(Math.max(r,t),i)}function b(r,t,i){let e=`translate3d(${r}px,${t||0}px,0)`;return i!==void 0&&(e+=` scale3d(${i},${i},1)`),e}function y(r,t,i,e){r.style.transform=b(t,i,e)}const $="cubic-bezier(.4,0,.22,1)";function R(r,t,i,e){r.style.transition=t?`${t} ${i}ms ${e||$}`:"none"}function L(r,t,i){r.style.width=typeof t=="number"?`${t}px`:t,r.style.height=typeof i=="number"?`${i}px`:i}function U(r){R(r)}function q(r){return"decode"in r?r.decode().catch(()=>{}):r.complete?Promise.resolve(r):new Promise((t,i)=>{r.onload=()=>t(r),r.onerror=i})}const _={IDLE:"idle",LOADING:"loading",LOADED:"loaded",ERROR:"error"};function G(r){return"button"in r&&r.button===1||r.ctrlKey||r.metaKey||r.altKey||r.shiftKey}function K(r,t,i=document){let e=[];if(r instanceof Element)e=[r];else if(r instanceof NodeList||Array.isArray(r))e=Array.from(r);else{const s=typeof r=="string"?r:t;s&&(e=Array.from(i.querySelectorAll(s)))}return e}function C(){return!!(navigator.vendor&&navigator.vendor.match(/apple/i))}let F=!1;try{window.addEventListener("test",null,Object.defineProperty({},"passive",{get:()=>{F=!0}}))}catch{}class X{constructor(){this._pool=[]}add(t,i,e,s){this._toggleListener(t,i,e,s)}remove(t,i,e,s){this._toggleListener(t,i,e,s,!0)}removeAll(){this._pool.forEach(t=>{this._toggleListener(t.target,t.type,t.listener,t.passive,!0,!0)}),this._pool=[]}_toggleListener(t,i,e,s,n,o){if(!t)return;const a=n?"removeEventListener":"addEventListener";i.split(" ").forEach(l=>{if(l){o||(n?this._pool=this._pool.filter(d=>d.type!==l||d.listener!==e||d.target!==t):this._pool.push({target:t,type:l,listener:e,passive:s}));const c=F?{passive:s||!1}:!1;t[a](l,e,c)}})}}function B(r,t){if(r.getViewportSizeFn){const i=r.getViewportSizeFn(r,t);if(i)return i}return{x:document.documentElement.clientWidth,y:window.innerHeight}}function S(r,t,i,e,s){let n=0;if(t.paddingFn)n=t.paddingFn(i,e,s)[r];else if(t.padding)n=t.padding[r];else{const o="padding"+r[0].toUpperCase()+r.slice(1);t[o]&&(n=t[o])}return Number(n)||0}function N(r,t,i,e){return{x:t.x-S("left",r,t,i,e)-S("right",r,t,i,e),y:t.y-S("top",r,t,i,e)-S("bottom",r,t,i,e)}}class Y{constructor(t){this.slide=t,this.currZoomLevel=1,this.center={x:0,y:0},this.max={x:0,y:0},this.min={x:0,y:0}}update(t){this.currZoomLevel=t,this.slide.width?(this._updateAxis("x"),this._updateAxis("y"),this.slide.pswp.dispatch("calcBounds",{slide:this.slide})):this.reset()}_updateAxis(t){const{pswp:i}=this.slide,e=this.slide[t==="x"?"width":"height"]*this.currZoomLevel,n=S(t==="x"?"left":"top",i.options,i.viewportSize,this.slide.data,this.slide.index),o=this.slide.panAreaSize[t];this.center[t]=Math.round((o-e)/2)+n,this.max[t]=e>o?Math.round(o-e)+n:this.center[t],this.min[t]=e>o?n:this.center[t]}reset(){this.center.x=0,this.center.y=0,this.max.x=0,this.max.y=0,this.min.x=0,this.min.y=0}correctPan(t,i){return I(i,this.max[t],this.min[t])}}const T=4e3;class k{constructor(t,i,e,s){this.pswp=s,this.options=t,this.itemData=i,this.index=e,this.panAreaSize=null,this.elementSize=null,this.fit=1,this.fill=1,this.vFill=1,this.initial=1,this.secondary=1,this.max=1,this.min=1}update(t,i,e){const s={x:t,y:i};this.elementSize=s,this.panAreaSize=e;const n=e.x/s.x,o=e.y/s.y;this.fit=Math.min(1,nIn this guide, we'll help you write your first program in Node.js. You'll create a simple HTTP server that listens on port 8080 and responds with "Hello, World!" when you visit http://localhost:8080
in your browser.
Before you begin, make sure you have Node.js installed on your machine. If you haven't installed Node.js yet, you can follow the steps in the installation guide.
Open your favorite text editor and create a new file. You can name it whatever you like, but for this example, let's call it hello.js
.
In your hello.js
file, type the following code:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.end('Hello World!');
+}).listen(8080);
+
After writing the code, save the file.
Open a terminal or command prompt and navigate to the directory where you saved hello.js
. Then, type the following command:
node hello.js
+
After running the command, your web server will start listening on port 8080. Open a web browser and navigate to http://localhost:8080
. You should see the text "Hello World!" displayed in the browser.
In this guide, we'll explore what Node.js is, how it works, and its various use cases.
Node.js is an open-source server environment that enables the execution of JavaScript code outside of a web browser. It's free, versatile, and runs seamlessly on various platforms including Windows, Linux, Unix, and macOS.
Unlike traditional web development, where JavaScript is mainly used for client-side scripting, Node.js enables you to execute JavaScript on the server-side.
At its core, Node.js is built on Chrome's V8 JavaScript engine, which makes it fast and efficient. It uses an event-driven, non-blocking I/O model, which means that it can handle thousands of simultaneous connections without getting bogged down by blocking operations.
One of the key reasons Node.js stands out is its asynchronous programming model. Traditionally, web servers would wait while performing tasks like opening files.
Node.js, however, sends tasks to the computer's file system and proceeds to handle the next request without waiting. This non-blocking, asynchronous approach enhances efficiency and responsiveness, making Node.js an excellent choice for handling concurrent operations.
Node.js files contain tasks that execute in response to specific events, such as a user attempting to access a port on the server. These files, typically denoted with a ".js" extension, must be initiated on the server to take effect.
',13);function p(u,m){const t=s("RouteLink");return n(),a("div",null,[h,i("p",null,[e("With this foundational understanding of Node.js, you're ready to dive deeper into its capabilities and explore "),r(t,{to:"/docs/"},{default:d(()=>[e("server-side JavaScript development")]),_:1}),e(".")])])}const j=o(c,[["render",p],["__file","what-is-nodejs.html.vue"]]),w=JSON.parse(`{"path":"/get-started/what-is-nodejs.html","title":"What is Node.js?","lang":"en-US","frontmatter":{"title":"What is Node.js?","index":true,"icon":"book-open","category":["Getting started"],"footer":false,"description":"In this guide, we'll explore what Node.js is, how it works, and its various use cases. Understanding Node.js Node.js is an open-source server environment that enables the execut...","head":[["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/get-started/what-is-nodejs.html"}],["meta",{"property":"og:site_name","content":"Node.js Docs"}],["meta",{"property":"og:title","content":"What is Node.js?"}],["meta",{"property":"og:description","content":"In this guide, we'll explore what Node.js is, how it works, and its various use cases. Understanding Node.js Node.js is an open-source server environment that enables the execut..."}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-04-15T20:12:13.000Z"}],["meta",{"property":"article:author","content":"Aahil"}],["meta",{"property":"article:modified_time","content":"2024-04-15T20:12:13.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"What is Node.js?\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-04-15T20:12:13.000Z\\",\\"author\\":[{\\"@type\\":\\"Person\\",\\"name\\":\\"Aahil\\",\\"url\\":\\"https://linktr.ee/thecr3ator\\"}]}"]]},"headers":[{"level":2,"title":"Understanding Node.js","slug":"understanding-node-js","link":"#understanding-node-js","children":[{"level":3,"title":"How Does Node.js Work?","slug":"how-does-node-js-work","link":"#how-does-node-js-work","children":[]},{"level":3,"title":"Why Node.js?","slug":"why-node-js","link":"#why-node-js","children":[]},{"level":3,"title":"Use Cases of Node.js","slug":"use-cases-of-node-js","link":"#use-cases-of-node-js","children":[]},{"level":3,"title":"Anatomy of a Node.js File","slug":"anatomy-of-a-node-js-file","link":"#anatomy-of-a-node-js-file","children":[]}]}],"git":{"createdTime":1713203996000,"updatedTime":1713211933000,"contributors":[{"name":"Aahil","email":"onyeanunaprince@gmail.com","commits":2}]},"readingTime":{"minutes":1.17,"words":350},"filePathRelative":"get-started/what-is-nodejs.md","localizedDate":"April 15, 2024","autoDesc":true}`);export{j as comp,w as data}; diff --git a/docs/.vuepress/dist/docs/Basics/Email.html b/docs/.vuepress/dist/docs/Basics/Email.html new file mode 100644 index 0000000..ed04f40 --- /dev/null +++ b/docs/.vuepress/dist/docs/Basics/Email.html @@ -0,0 +1,78 @@ + + + + + + + + + +In this tutorial, we'll explore how to use the Nodemailer module to send emails from your Node.js server.
The Nodemailer module simplifies the process of sending emails from your computer. You can easily download and install the Nodemailer module using npm:
npm install nodemailer
+
After installing the Nodemailer module, you can include it in any application:
var nodemailer = require('nodemailer');
+
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:
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.
To send an email to multiple receivers, simply add them to the to
property of the mailOptions
object, separated by commas:
var mailOptions = {
+ from: 'youremail@gmail.com',
+ to: 'myfriend@yahoo.com, myotherfriend@yahoo.com',
+ subject: 'Sending Email using Node.js',
+ text: 'That was easy!'
+}
+
If you want to send HTML-formatted text in your email, use the html
property instead of the text
property:
var mailOptions = {
+ from: 'youremail@gmail.com',
+ to: 'myfriend@yahoo.com',
+ subject: 'Sending Email using Node.js',
+ html: '<h1>Welcome</h1><p>That was easy!</p>'
+}
+
That's all you need to know to start sending emails from your Node.js server using the Nodemailer module.
In this tutorial, we'll explore how Node.js is ideal for building event-driven applications.
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:
var fs = require('fs');
+var rs = fs.createReadStream('./demofile.txt');
+rs.on('open', function () {
+ console.log('The file is open');
+});
+
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:
var events = require('events');
+var eventEmitter = new events.EventEmitter();
+
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.
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');
+
In this tutorial, we'll explore how to work with the file system on your computer using Node.js.
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:
var fs = require('fs');
+
The fs.readFile()
method is used to read files on your computer. Let's see an example of reading an HTML file:
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);
+
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:
var fs = require('fs');
+
+fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
+ if (err) throw err;
+ console.log('Saved!');
+});
+
var fs = require('fs');
+
+fs.open('mynewfile2.txt', 'w', function (err, file) {
+ if (err) throw err;
+ console.log('Saved!');
+});
+
var fs = require('fs');
+
+fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
+ if (err) throw err;
+ console.log('Saved!');
+});
+
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:
var fs = require('fs');
+
+fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
+ if (err) throw err;
+ console.log('Updated!');
+});
+
var fs = require('fs');
+
+fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
+ if (err) throw err;
+ console.log('Replaced!');
+});
+
var fs = require('fs');
+
+fs.unlink('mynewfile2.txt', function (err) {
+ if (err) throw err;
+ console.log('File deleted!');
+});
+
To rename a file, use the fs.rename()
method:
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 📁
Let's explore how Node.js utilizes the built-in HTTP module to transfer data over the Hyper Text Transfer Protocol (HTTP).
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:
var http = require('http');
+
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:
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.
To display the response from the HTTP server as HTML, include an HTTP header with the correct content type:
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.
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:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.write(req.url);
+ res.end();
+}).listen(8080);
+
You can easily split the query string into readable parts using the built-in URL module:
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);
+
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.
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.
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:
var http = require('http');
+
Now your application has access to the HTTP module, allowing you to create a server like this:
http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.end('Hello World!');
+}).listen(8080);
+
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:
// myfirstmodule.js
+
+exports.myDateTime = function () {
+ return Date();
+};
+
Use the exports
keyword to make properties and methods available outside the module file.
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:
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:
C:\Users\Your Name>node demo_module.js
+
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.
The NPM program comes pre-installed on your computer when you install Node.js, making it readily available for use without any additional setup.
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.
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:
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.
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:
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:
// 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:
C:\Users\Your Name>node demo_uppercase.js
+
In this tutorial, we'll explore how Node.js uses the built-in URL module to parse web addresses.
The URL module in Node.js helps split a web address into readable parts. To include the URL module, use the require()
method:
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:
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'
+
Now, let's combine our knowledge of parsing query strings with serving files using Node.js as a file server.
Create two HTML files, summer.html
and winter.html
, and save them in the same folder as your Node.js files.
<!DOCTYPE html>
+<html>
+<body>
+<h1>Summer</h1>
+<p>I love the sun!</p>
+</body>
+</html>
+
<!DOCTYPE html>
+<html>
+<body>
+<h1>Winter</h1>
+<p>I love the snow!</p>
+</body>
+</html>
+
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:
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:
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 will display:
Summer
+I love the sun!
+
http://localhost:8080/winter.html will display:
Winter
+I love the snow!
+
In this tutorial, we'll explore how to upload files to your Node.js server using 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:
C:\Users\Your Name>npm install formidable
+
Once installed, you can include Formidable in your application:
var formidable = require('formidable');
+
Now, let's create a web page in Node.js that allows users to upload files to your server.
First, create a Node.js file that generates an HTML form with an upload field:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
+ res.write('<input type="file" name="filetoupload"><br>');
+ res.write('<input type="submit">');
+ res.write('</form>');
+ return res.end();
+}).listen(8080);
+
To handle the uploaded file, include the Formidable module:
var formidable = require('formidable');
+
Then, parse the uploaded file:
var form = new formidable.IncomingForm();
+form.parse(req, function (err, fields, files) {
+ res.write('File uploaded');
+ res.end();
+});
+
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:
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();
+});
+
Welcome to the Node.js Documentation! In this comprehensive resource, you'll find detailed explanations of various Node.js concepts and functionalities. Let's explore the different sections together.
In the Basics section, you'll find essential topics that form the foundation of Node.js development. Here are some of the key topics covered:
In the MongoDB section, you'll delve into MongoDB integration with Node.js. Topics include:
In the MySQL section, you'll find in-depth information about using MySQL with Node.js. Whether you're a beginner or an experienced developer, you'll find valuable insights into working with MySQL databases. Some of the topics covered include:
In the Raspberry Pi section, you'll discover Node.js applications on Raspberry Pi. Topics include:
Get ready to level up your Node.js skills with our comprehensive documentation! 🚀
Hello there! 👋🏾 Welcome to the Node.js documentation! Let's get you started on how to navigate through this resource.
In the Get started section, you'll find helpful guides to assist you in your Node.js journey. Whether you're looking to install Node.js, get started quickly with running your first application, or understand the core concepts of Node.js, you'll find everything you need here.
In the Docs section, you'll find detailed explanations of the fundamental concepts of Node.js. Whether you're interested in learning about Node.js modules, file system operations, or events, you'll find everything you need here.
This course is structured to help you learn Node.js by doing. Under each concept in the Docs section, you'll find examples that demonstrate how to apply the concepts in practice. The examples will look like this:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/plain'});
+ res.end('Hello World!');
+}).listen(8080);
+
There are also some types of examples that you'll need to run via the command line. These examples will look like this:
console.log('This example is different!');
+console.log('The result is displayed in the Command Line Interface');
+
And that's it! You're all set to start your Node.js journey. If you have any questions or need help, feel free to reach out to us on Twitter or GitHub - we're here to help! 🚀
In this guide, we'll walk you through the process of installing Node.js on your system so you can start building awesome applications.
There are several way to install Node.js, including using a package manager, downloading prebuilt binaries, or building from source. In this guide, we'll cover the most common method of installing Node.js using the official installer.
Visit nodejs.org and download the appropriate installer for your operating system (Windows, macOS, or Linux).
Once the download is complete, run the installer and follow the on-screen instructions. The installer will guide you through the installation process, including selecting the installation directory and any additional options you may want to configure.
After the installation is complete, you can verify that Node.js and npm (Node Package Manager) are installed correctly by opening a terminal or command prompt and typing the following commands:
node -v
+npm -v
+
These commands will display the versions of Node.js and npm installed on your system. If you see version numbers displayed, congratulations! You've successfully installed Node.js.
It's a good idea to keep npm up to date. You can do this by running the following command:
npm install npm@latest -g
+
This will update npm to the latest version available.
That's it! You've now installed Node.js on your system. You're ready to write your first Node.js program.
Note
If you ran into any issues during the installation process, feel free to report them on the Node.js GitHub repository
In this guide, we'll help you write your first program in Node.js. You'll create a simple HTTP server that listens on port 8080 and responds with "Hello, World!" when you visit http://localhost:8080
in your browser.
Before you begin, make sure you have Node.js installed on your machine. If you haven't installed Node.js yet, you can follow the steps in the installation guide.
Open your favorite text editor and create a new file. You can name it whatever you like, but for this example, let's call it hello.js
.
In your hello.js
file, type the following code:
var http = require('http');
+
+http.createServer(function (req, res) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.end('Hello World!');
+}).listen(8080);
+
After writing the code, save the file.
Open a terminal or command prompt and navigate to the directory where you saved hello.js
. Then, type the following command:
node hello.js
+
After running the command, your web server will start listening on port 8080. Open a web browser and navigate to http://localhost:8080
. You should see the text "Hello World!" displayed in the browser.
Congratulations! 🎉 You've just created and ran your first Node.js web server. Now get ready to understand how Node.js works
In this guide, we'll explore what Node.js is, how it works, and its various use cases.
Node.js is an open-source server environment that enables the execution of JavaScript code outside of a web browser. It's free, versatile, and runs seamlessly on various platforms including Windows, Linux, Unix, and macOS.
Unlike traditional web development, where JavaScript is mainly used for client-side scripting, Node.js enables you to execute JavaScript on the server-side.
At its core, Node.js is built on Chrome's V8 JavaScript engine, which makes it fast and efficient. It uses an event-driven, non-blocking I/O model, which means that it can handle thousands of simultaneous connections without getting bogged down by blocking operations.
One of the key reasons Node.js stands out is its asynchronous programming model. Traditionally, web servers would wait while performing tasks like opening files.
Node.js, however, sends tasks to the computer's file system and proceeds to handle the next request without waiting. This non-blocking, asynchronous approach enhances efficiency and responsiveness, making Node.js an excellent choice for handling concurrent operations.
Node.js files contain tasks that execute in response to specific events, such as a user attempting to access a port on the server. These files, typically denoted with a ".js" extension, must be initiated on the server to take effect.
With this foundational understanding of Node.js, you're ready to dive deeper into its capabilities and explore server-side JavaScript development.
+ |
+ Priority | +Change Frequency | +Last Updated Time | +
---|---|---|---|
+ |
+
+ |
+
+ |
+
+ |
+