Web-NodeJs module

Modules in NodeJS

Now we will explore how to use modules in NodeJS.

        Modules in NodeJS can be accomplished by using Node’s  require()  function. Using require() we can do the following:

  • We can load modules belonging to Node.js. These include the HTTP module, which allows us to make a web server, and the fs module, which allows us to access the computer's file system
  • Likewise, we can use require() to load third-party libraries such as Express, which will reduce the amount of code we have to write. It is often useful to use pre-written libraries to solve complex problems, so all we need to do is implement the require() function and call the relevant methods.
  • Furthermore, we can even require our own code using the require() method. By using this technique we will be able to split our application into multiple smaller files which is crucial for developing real applications.

        Use cases for require() can be provided in the section named Filesystem (fs) module below.

        Sometimes, your application may need to read the location of a file or directory, for this you can use the following command

// to access the current directory
console.log(__dirname);

// to access the current file path
console.log(__filename);

        In Node.js, the require() function is used to load a module and import the contents of the module into the currently running script. It accepts a string parameter that specifies the path to the module to load.

        The require() function has the following uses:

        1. Load the Node.js core module: When the name of a Node.js core module is passed to require(), Node.js will find the module and load it. For example, to load the fs module (for file operations), you can use require('fs').

        2. Load third-party modules: When the name of a third-party module is passed to require(), Node.js will find the module in the node_modules folder of the current project and load it. For example, to load the Express framework module, you can use require('express').

        3. Load custom modules: When a relative or absolute path is passed to require(), Node.js will load the custom module according to the path. If it is a relative path, Node.js will resolve the path based on the location of the current script. For example, to load the myModule.js module located in the same directory as the current script, you can use require('./myModule').

        4. Load the JSON file: When a file path ending with ".json" is passed to require(), Node.js will automatically parse and import the JSON file. For example, to load the config.json file located in the same directory as the current script, you can use require('./config.json'). Note that the require() function caches the loaded module when it is first executed, so that subsequent calls can use the cached module directly without loading it again. If you want to reload the module, you can use the delete keyword to delete the cached module object and then call the require() function again.

Http and https modules

        Node.js provides a built-in module HTTP that can be used to transfer data over HTTP. You must use the http module in node to use the HTTP server. Using the HTTP module, the client can access the server's port and receive a response.

var http = require('http');

        But if we need a secure http module then we will have to ask for the https module

var https = require('https');

        Here is an example:

// To create a server
http.createServer((request, response)=>{
   
    // Sends a chunk of the response body
    response.write('Hello World!');
   
    // Signals the server that all of
    // the response headers and body 
    // have been sent
  response.end();
})
.listen(3060); // Server listening on port 3060

Readline module

        The Readline module allows users to read data from a readable stream (such as process.stdin) one line at a time. The code below demonstrates the read line module.

var readline = require('readline');

var ask = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

ask.question(">>What's the year?  ", answer => {
  console.log(`Its `+answer);
  ask.close();
});

        Readline interfaces are created by calling createInterface() and passing at least readable and writable streams. Input is provided by process.stdin (the standard input stream), and output is provided by process.stdout.

        The function question() posts a question and then provides a callback function to handle the response. Use the function close() to close the interface.

File System (fs) module

        Next, we will discuss the file system (fs) module and go through the process of creating and adding files to the system.

        Using the fs module, users can interact with the file system using POSIX-compliant methods. Portable Operating System Interface (POSIX) is a set of standard operating system interfaces based on the Unix operating system.

        The fs module provides the appendFile() function for asynchronous file operations, or the appendFileSync() function for synchronous file operations.

        The syntax of appendFile() function is

fs.appendFile(filepath, data, options, callback_function);

        The callback function is required and is called when data appending is completed successfully.

  • filepath is a string specifying the path to the file and is required
  • data  is the data you append to the file and is required
  • options is to specify the encoding/mode/flag, which is optional

        Create a new file: append.js and file.txt and put them in the same folder.

        In append.js, include the following code

const fs = require('fs');
const data = "\nThis data is for appending.";
 
fs.appendFile('file.txt',data, 'utf8',
    // callback function
    function(err) {     
        if (err) throw err;
        // if no error
        console.log("Successful")
});

        The fs module contains other functions such as open() and writeFile(). For more exercises, you can refer to the following resources.

Operating System (os) module

        The OS module contains information about the computer's operating system, such as the name of the operating system and the name of the current user.

        Syntax for operating system modules:

const os = require('os');

        There are some proprietary and methods in OS modules like userInfo() to access information about the current user. See the code below to access the withholding of the username.

const os = require('os');
const fs = require('fs');

var user = os.userInfo();

var data = "\hello " ; 

fs.appendFile('file.txt',data + user.username + "\n",'utf8',
    // callback function
    function(err) {     
        if (err) throw err;
        // if no error
        console.log("Successful")
});

Path module

The path module provides a variety of useful functions         when it comes to accessing and interacting with the file system .

var path = require('path');

        Depending on the operating system your Node.js application is running on, the node:path module operates differently by default. For example, when running on a Windows operating system, the node:path module assumes that Windows-style paths are being used. For consistent results when using Windows file paths on any operating system, use  path.win32

        Here are some useful methods of the path module :

path.basename(path): This method returns the last segment of the path.

path.dirname(path):  This method returns the directory name for a specific path.

path.extname(path):  The path extension returned by this method. (dot) character to the end of the string in the last part of the path.

path.isAbsolute(path): This method determines whether a path is an absolute path

var path = require('path');
var filename = path.basename('httpserver/server.js');
var dirname = path.dirname('httpserver/server.js');
var extension_name = path.extname('httpserver/server.js');
var abs_path = path.isAbsolute('httpserver/server.js');

console.log(filename);
console.log(dirname);
console.log(extension_name);
console.log(abs_path);

URL module

        Use the URL module to divide URLs into readable chunks.

var url = require('url');

        Let's look at an example of splitting a URL into readable parts:

var url = require('url');
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'
console.log(qdata.year); //returns '2017'

Querystring module

        The purpose of this module is to provide utilities for parsing and formatting URL query strings.

var querystring = require('querystring');

        Let's look at an example of parsing the query string into an object and extracting the year attribute:

var q = querystring.parse('year=2017&month=february');
console.log(q.year);
console.log(q.month);

Guess you like

Origin blog.csdn.net/qq_54813250/article/details/133416381