A Preliminary Study on nodeJS and nodejs

Source: Internet
Author: User
Tags node server

A Preliminary Study on nodeJS and nodejs

I. Preface

In the "explore nodeJS" article, we have a general understanding of node, and finally through an example, we learned how to quickly start a simple server.

Today, I read this article again, and found that this article has a little more theoretical knowledge. It is suitable for beginners of node and has a fixed idea. I want to write this article in my mind, by writing a slightly larger node example step by step, we can have a more comprehensive understanding of the node as a whole.

So, this article is based on "exploring node. js" and is named "exploring node. js ".

Okay, so what kind of example will we implement soon?

Example:

The user enters the login page through 127.0.0.1/login of the url. After the user enters the account name (it doesn't matter if the password option is not lost, just to make the page reasonable), click Submit to go to the home page.

What should I do on the node server? Based on the URL, when it is/login, the service reads the content of login.html and transmits it to the front-end display. When it is replaced by the template in/login, the result is finally transmitted to the front-end display.

The general process is as follows:

The final result of the example is as follows:

Now, let's take a step-by-step implementation of the Demo.

Ii. Prepare front-end files

To implement the above-mentioned results, we should first simply upload two pages: login.html?home.html and a New Year's image, which is obvious for the node to read and present them to the browser for use.

In the above description, we have already mentioned that the nodeserver is used to write the form action './home' in login.html to achieve our purpose. The request method is post.

In addition, because we need to combine the account name entered in login.html with home.html, the "name" position in fixed home.html cannot be written to death, so we use {name} to hold the space, and then use node to dynamically replace it.

Easy to compile, The login.html?home.html and the New Year's map are as follows:

<! DOCTYPE html> 
<! DOCTYPE html> 

3. Compile the node service

In the above process, we have prepared the required front-end files. Next we will use node to write services and concatenate them.

First, we construct a main file named main. js. Its function is self-evident. The main entry point is: if we want to start the service after code is compiled, we will focus on node main. js is OK.

As follows:

'Use strict '; var http = require ('http'); var server = http. createServer (); server. on ('request', function (req, res) {// exclude favicon. ico request if (req. url! = '/Favicon. ico ') {// TODO} else {res. end ();};}). listen ('80'); console. log ('server running! ');

Next, we will gradually improve the main file.

In the preface, we mentioned that when a request comes to the service, we take the URL path to determine the next operation, which has reached the goal of reducing coupling.

Therefore, in the main program, we use the url module to obtain the relevant path in the url, obtain the first path through regular expressions, and process it through the next routing module.

As follows:

'Use strict '; var http = require ('http'); var url = require ('url'); var server = http. createServer (); server. on ('request', function (req, res) {if (req. url! = '/Favicon. ico ') {// obtain the path let pathname = url. parse (req. url ). pathname; pathname = pathname. match (/\ w +/) [0]; // specific router, to be written... router [pathname] (req, res);} else {res. end ();};}). listen ('80'); console. log ('server running! ');

Now, let's write the router module together.

In our example, the router process login, home, and image request getPic. Therefore, the basic skeleton of the router module is tentatively set as follows:

'use strict';var router = { login: function(req, res){ //TODO  }, home: function(req, res){ //TODO }, getPic: function(req, res){ //TODO }};module.exports = router;

In addition, we found that login, home, And getPic have many similarities, such as reading local files on the server and writing the files to the response body, we extract these operations as the operation module.

In the operation module, we need to use the node built-in 'fs' module to read files. The 'fs' module will use the following method:

1. fs. readFileSync -- synchronously reads files

2. fs. readFile -- asynchronously reads files

3. fs. writeFileSync -- synchronous file writing

4. fs. writeFile -- asynchronously write files

Note that fs. readFileSync/fs. readFile is used to read the image. However, the second parameter still needs to be added with 'binary 'and binary.

'Use strict '; var fs = require ('fs'); var operationFile = {readFileSync: function (path, callback) {// synchronously read the file let data = fs. readFileSync (path, 'utf-8'); syncOperation (callback, data, 'synchronized read file');}, readFileAsync: function (path, callback) {// asynchronously read the file fs. readFile (path, function (err, data) {asyncOperation (err, callback, data, 'asynchronous File Read successfully') ;}, writeFileSync: function (path, data, callback) {// synchronously write to the file fs. writeFileSync (path, data); syncOperation (callback, null, 'synchronized write file');}, writeFile: function (path, data, callback) {// Write File fs asynchronously. writeFile (path, data, function (err) {asyncOperation (err, callback, null, 'asynchronous file writing completed ') ;}, readImg: function (path, callback) {// asynchronously read the image fs. readFile (path, 'binary ', function (err, file) {asyncOperation (err, callback, file, 'asynchronous image reading completed ');});}}; function syncOperation (callback, data, msg = 'Operation successfully') {if (typeof callback = 'function') {callback (data);} else {console. log (msg) ;}} function asyncOperation (err, callback, data, msg = 'Operation successfully') {if (err) {console. log (err);} else if (typeof callback = 'function') {callback (data);} else {console. log (msg) ;}} module. exports = operationFile;

Operation Module

In additionWhen we use the post request when submitting a form in login.html, how should we receive the transmitted entities in the node service?

Node uses the 'data' listener to receive object information of the post method, and uses 'end' to listen for events that have completed receiving information.

Node receives get request parameters, which is not so complex. You can directly obtain the query string after the url.

Okay., We will get the parameters of post and get requests, and write them into a module named getQuery, as shown below:

'use strict';var url = require('url');var querystring = require('querystring');module.exports = { fromGet: function(req, res, callback){ var data = url.parse(req.url, true).query; callback(data);  }, fromPost: function(req, res, callback){ var data = ''; req.on('data', function(chunk){  data += chunk; }); req.on('end', function(){  data = querystring.parse(data);  callback(data); }); }};

GetQuery Module

LastThe operation and getQuery modules are introduced in the router module to improve the login, home, And getPic methods.

Note that the getPic method is used to process images. Therefore, the Response Header must be written as 'image/jpeg ', as shown below:

res.writeHead(200, {'Content-Type':'image/jpeg'});

Okay. The general idea has been clarified. For detailed code, see github.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

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.