Nodejs 0 Basic Detailed tutorial 2: modular, FS file Operation module, HTTP Create service module

Source: Internet
Author: User
Tags readfile install node

Chapter II recommended study time 4 hours course Total 10 chapters

How to learn: read it in detail and implement the relevant code manually

Learning Goals : This tutorial will teach you to install node, build servers, express, mysql, mongodb, write background business logic, write interfaces, and finally complete a complete project backstage, a total of 10 days is Expected.

Module Retroflex suffixation

Why do I need module retroflex suffixation?

Our previous conventional JS code, we in order to reuse some JS code, is the JS method encapsulated, put into the JS file, and then introduced in the HTML page js, you can use these methods in the Page.

When this direct introduction and invocation of the way there are some unfriendly places, for example, 1, if the two JS in the name of the method, will produce Coverage. 2, if one JS need to call another JS method, then the order of JS introduced there are restrictions, such as when we use jquery generally in the front of JS to Introduce.

This has the need for modularity: separate JS into a single module, avoiding duplicate names and not having to consider introducing sequential Issues.

    • Node. JS adheres to the COMMONJS specification (this is just a code-writing specification for a module retroflex suffixation, with specific details that you can search for yourself, and then we write the specific Code)

So how to implement module Retroflex suffixation?

We are in one of our own folders (example nodetest), first create a folder module, in which create Module01.js module02.js test.js, after the creation of the directory structure as Follows:

The implementation of module Retroflex suffixation requires three steps:

1. Write the module and expose the interface

Write the following code in module01.js, write two methods, and expose the interface outward using the module object that comes with Node.

(code explanation: The Module object is a node retroflex suffixation object, which has an empty object under the default object-exports, we will need to expose the object directly assigned to the exports to expose the interface, the next step will explain how to use the Interface)

function fn01 () {  // Write a method fn01    console.log ("module01-fn01");} function fn02 () {  // Write a method fn02    console.log ("module01-fn02");} // Exposed interface module.exports = {    "fn01": fn01,    "fn02": fn02}

2. Using the interface

Write the following code in the Test.js

var // introduce the module using require and declare a variable to receive the object exposed by the interface  // Access interface Exposure method

Explanation: (1) using the Node-band method require introduces the module, the format require ("file path"), "here./represents the current path", () then we declare a variable MODULE01 to receive the object exposed by the introduction module, This object is the object that we assigned to exports in the previous step, with the following relationship:

Module01 = = {
"fn01": fn01,
"fn02": FN02
}

Now that we have received this object using module01, we can invoke the method or property Inside. Using Module01.fn01 (), You can perform the Fn01 method in Module01.js.

3, the operation to see the effect

When using node to run test.js, you can see the Fn01 method to perform the printing "module01-fn01";

References to multiple modules

We've only introduced Module01.js in the last step, and We've introduced multiple modules

1, We first put module02.js also written interface, code and module.js basically consistent, just printed content changed to "module02-fn01"

function fn01 () {  // Write a method fn01    console.log ("module02-fn01");} function fn02 () {  // Write a method fn02    console.log ("module02-fn02");} // Exposed interface module.exports = {    "fn01": fn01,    "fn02": fn02}

2, we introduce the module in the Test.js

Modify the original Test.js code to the following code:

var // Module01.js exposed objects use variable MODULE01 to receive var // Module02.js exposed objects use variable MODULE02 to receive  / /how to access module01.js // methods of accessing Module02.js

3, the implementation of Test.js

Can see the two modules are called, and here we can see, even if the module used the same method, in use, because the definition of different variables to receive, it does not affect each other, and we have to use which module directly reference can be, this is the advantage of module retroflex Suffixation.

Another method of module retroflex suffixation exposing the interface

Directly attaches the method that needs to be exposed to the exports object as an Attribute. The effect is the same as the above method, Let's modify the Module02.js code

function fn01 () {  // Write a method fn01    console.log ("module02-fn01");} function fn02 () {  // Write a method fn02    console.log ("module02-fn02");} // Exposed interface Export.fn01 == fn02;

When you run test.js, the effect is the same as the previous Step.

FS File Operation module

Read file

Node comes with the file Operation module fs, which only needs to be introduced directly when using

First create the file fs01.js a.txt file

Edit A.txt. Arbitrary write point text (note that the encoding format is modified to UTF-8)

Edit the fs01.js, write the Code (the code is interpreted after the effect is Running)

var // the node built-in module can be directly introduced into  fs: file system operation module fs.readfile ("./a.txt", "utf-8",function(err,data) {  // Read File     console.log (err,data);});

run, you can see the display, the first arrow null means no error, the second arrow indicates the A.txt internal content of the read

Explanation: the first line of code we introduced Node's own module FS (file manipulation Module)

The second line of code calls the Read file method under the FS module readFile, internally passed in three parameters, 1, read the file path, 2, encoding format, 3, callback function, There are two parameters err and data in the callback function, err represents the error message, when the file read error will be assigned the wrong value The data indicates the contents of the file being read by a false hint.

In general, we need to throw an exception termination program if there is a read Error. So you need to modify the code as follows

var // the node built-in module can be directly introduced into  fs: file system operation module fs.readfile ("./a.txt", "utf-8",function(err,data) {  // Read File    if Throw err;    Console.log (err,data);     // the subsequent operation of the read can be written here });

Write file

Using the WriteFile method

Writes the data read from the previous step to the B.txt file

Description : Subsequent I have directly modified Fs01.js code to demonstrate, you can create a new JS file yourself to write code and Execution.

Modify the Fs01.js code as follows (add code to write to the file in the middle):

var // the node built-in module can be directly introduced into  fs: file system operation module fs.readfile ("./a.txt", "utf-8",function(err,data) {  // Read File    if Throw err;     // the subsequent operation of the read can be written here    Fs.writefile ("./b.txt", data,function(err) {  // write to file        if Throw err;    })});

Explanation: the WriteFile method has three parameters, 1, the file path to write (if there is no such file, node will automatically create a b.txt), 2, the data that needs to be written (we will pass the data read from A.txt to b.txt), 3, the callback function, only one parameter, Error message when a write error occurs, err

Execute fs01.js to see a new b.txt added to the current folder. And the content is written internally

WriteFile is to replace the content, if you want to append the write, you can use the AppendFile method

We modify the fs01.js in the Write method to AppendFile

Then execute the fs01.js multiple times

Then open b.txt and you can see that the content has been written multiple times

to Delete a file , use the Unlink method

var // node built-in module can be directly introduced into  fs: file system operation module fs.unlink ("./b.txt",function(err) {  //  Delete file    ifthrow  Err;})

The Unlink method has two parameters, 1, the path to delete, 2, the callback function, and if there is an error, err prompt

Modify the Fs01.js content for the above code, and then execute fs01.js, and you can see that B.txt was deleted

Create a folder

Using the MkDir method, the method has two parameters 1, folder name, 2, callback function, If there is an error, there will be Err prompt

Modify the Fs01.js content to the following code, and then execute fs01.js to see that a folder named C is created in the current folder

var // node built-in module can be directly introduced into  fs: file system operation module fs.mkdir ("c",function(err) {  // Create c file     Ifthrow  Err;})

Modify File Name/folder Name

Using remane, the method has two parameter 1, the file name to be modified (under the current directory), 2, the new file name, 3, callback function, If there is an error, there will be Err prompt

Modify the Fs01.js content for the following code, and then execute fs01.js, and you can see that the folder C name in the current folder is modified in order to D

var // the node built-in module can be directly introduced to  fs: file system operation module fs.rename ("c", "d",function(err) {  // C Change folder name to  D    ifthrow  Err;})

Modify the Fs01.js content for the following code, and then execute fs01.js, and you can see that the file A.txt name in the current folder is modified in order to D.txt

var // node built-in module can be directly introduced into  fs: file system operation module fs.rename ("a.txt", "d.txt",function(err) {  //  Change a.txt to  d.txt    ifthrow  Err;})

HTTP module, creating a background server

Node comes with the module HTTP that creates the service, which you only need to introduce directly when you use it.

First create the file http01.js, and then add the following code

var http = require ("http"); http.createserver (function(request,response) {        Console.log (// response.end ("haha") to print this message back to the console when the browser is accessed    ;   Indicates the end of the request and returns the result to the browser }). Listen (3000);

Description

first, the HTTP module is introduced,

Then call the Createserver method to create the service, there is only one parameter (callback function: indicating that the request occurs when the code needed to execute "back to the function has two parameters, 1, request information, 2, the corresponding information"),

Finally need to add port listening listen (custom Port number, Here we use 3000),

Run http01.js, If there is no error, it means that the service has been started, and then enter http://localhost:3000/in the browser can access the server, will show the returned "hehe" text;

Note: after starting the service, and then modify the JS file, will not be directly updated to the page, the command line needs to press CTRL + C to end the run, and then rerun the js, then refresh the browser, to see the Effect.

When you visit, look at the console and you'll see the printed information

Read a file and transfer it to a page

In the current folder, create a a.txt file, write a text

Then modify the code for Http01.js as follows, and then run to write the read a.txt data to the page

var http = require ("http"); // introducing the HTTP module var // Introducing the FS module http.createserver (function(request,response) {        fs.readfile ("./a.txt", "utf-8", function (err,data) {  // Read file       ifthrow  err;       Response.End (data); // indicates the end of the request and returns the result to the browser    });}). Listen (3000);

ok, so much for today, tomorrow will explain: NPM package management, git GitHub use.

Nodejs 0 Basic Detailed tutorial 2: modular, FS file Operation module, HTTP Create service module

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.