Nodejs for an online form-filling application

Source: Internet
Author: User
Tags readfile

1. Build a Web server

Used to play PHP and JSP used Apache, Tom Cat Server, Nodejs is different, he needs his own createserver.

  

Server.js
var http = require (' http '); Http.createserver (function (req,res) { res.writehead (200,{' content-type ': ' Text/plain '}); Res.end (' so easy! ');}). Listen (1111, ' 127.0.0.1 '); Console.log (' Server runing at 127.0.0.1:1111 ... ');

You can see so easy! in the browser access 127.0.0.1:1111 Words.

Here the use of the HTTP module to the Createserver method, node module has three kinds, own module, NPM module, file module. Own module directly with require, without path, NPM module first to NPM install, and then introduced as the own module, the file module is to create their own modules, with the introduction of the path.

2. Get something from the request object

Above to Req is a request object, contains the request related to the information, can console.log out to see, more, here simple introduction.

(1) Req.url

Access http://127.0.0.1:1111 whose value is/

Access HTTP://127.0.0.1:1111/INDEX/INDEX.HTML?A=1#FD its value is/index/index.html?a=1 (note there is no hash here)

In general, the URL module to parse its path, with the QueryString module to parse its query parameters, of course, it is possible to decompose the string itself.

3. Respond

1 medium to Res is HTTP. An instance of the Clientrequest class, he has many methods. Here are two of them.

(1) Writehead (status,{' key ': value}); This method is used to write responses to header headers.

  

var http = require (' http '); Http.createserver (function (req,res) {    res.writehead (200,{' content-type ': ' text/html ') });    Res.end ("

If this is written, the resulting response to the head of Content-type is text/html, and the response data is parsed as HTML code.

(2) End ()

This method is used in the above example to write data to the data segment of the response message.

4. Read and Write files

The FS module used to read and write files.

(1) Read the file

Fs.readfile (file[, Options], callback): Asynchronously reads a file, the callback function has two parameters, the first error message, and the second is the data read. The data can be either a buffer or a string. Depending on the options to encoding

Fs.readfilesync (file[, Options]): Synchronously reads the file, returns the read to the data

Specifically, you can look at the documentation, about synchronization and asynchrony, Big ~ Bear understand not too deep, also often because of this mistake. Synchronization is a kind of blocking, you must read the back of the matter before you can do, asynchronous non-blocking, one thing did not finish behind the things can be done.

I built a 1.txt file under the project root directory, with the content "Welcome to Big ~ Bear";

var fs = require (' FS '); Console.log (Fs.readfilesync (__dirname+ '/1.txt ', ' UTF8 ')); Encoding was specified
Welcome to Big ~ Bear

  

var fs = require (' FS '); Console.log (Fs.readfilesync (__dirname+ '/1.txt ')); No designation Encoding//<buffer e6 ac A2 E8 bf 8e e5 B3 e6 b3 a8 e5 a4 A7 EF bd 9e E7

The Async method is similar

var fs = require (' FS '); Fs.readfile (__dirname+ "/1.txt", ' UTF8 ', function (err,data) {    console.log (data)})

(2) Writing files

Fs.writefile (file, data[, Options], callback), asynchronous Api,data can be buffer or string

Fs.writefilesync (file, data[, Options]), Sync API

    

var fs = require (' FS '); Fs.writefilesync (__dirname+ '/1.txt ', ' Big Bear is so handsome! ', ' UTF8 ');

You can see the contents of the file become ' Big Bear really handsome! “.

5. NODE-XLSX Module and Socket.io module

The former is to help us with the Excel table, please see HTTPS://GITHUB.COM/MGCREA/NODE-XLSX

The latter encapsulates the API for real-time communication, see Https://github.com/socketio/socket.io

Second, online application development of filling 1, the completion of the effect

  

There is still a problem in recording gif, that is, a user to modify a row, B users will not immediately display the changed data, has been corrected, the original time unicast event, changed to broadcast just fine. The original plan is to post the code to analyze the analysis, but considering that a large piece of code does not seem very good, so put it on GitHub https://github.com/yibingxiong/onlinetable/, the following only briefly talk about the idea, If you need to see the source code can clone, my GitHub currently does not have star, if you can become the first star, Big ~ Bear very happy.

2. Basic ideas

(1) When the user first link to the server to send a Connectin event, this event is called the IO () method is automatically sent to the server, without the need for active calls, the server accepts the event after reading the Excel file, and with NODEX-XLSX parsing, Then call the custom Changestatus method, which is based on the array of rows being modified Isoptrows (the array is shared by all users, storing the row to row number being modified) to add an identity to each row, 0 means no one is being modified, and 1 means someone is modifying it. When processing is complete, unicast a ServerChange event to the client and carry the processed data, the client renders the table based on the data, places the row with the status 0 in an editable state, and the row with the status 1 is not editable.

(2) When the user clicks Edit, sends a enter event to the server, and carries the data as the line number to be edited. It then turns the row data into an edit state, which becomes a text box and the button becomes complete. After the server receives the Enter event, it obtains the line number, joins the Isoptrows array, and then broadcasts an event broadcast, carrying the uplink number, informing all users that "this line is edited, you do not edit", the client receives this event, the line becomes non-editable state.

(3) When the user clicks Done, sends a DataChange event to the server, carries the modified to the new data, and turns the line into a normal state. After the server receives the DataChange event, the data for the corresponding row is updated and written back to the file. After writing, send a ServerChange event and carry the new data. The line number of the modified row is also overflowed from the isoptrows.

(4) The idea summarizes, realizes or compares the simple, but uses this example still can learn how to carry on the real-time communication, Socket.io actually is in the server and the client has established a communication channel. If you think of a server as a leader, the client as an employee can be understood as a leader who can issue instructions to a single employee (unicast), an employee assembly, an instruction (broadcast) to the employee employed, and, in turn, the employee can reflect the situation to the leader.

Third, talk about the experience of getting started Nodejs

JavaScript is a wonderful, Nodejs is a wonderful. Inside JavaScript You can set a function inside a function, his inheritance is based on the prototype, his array when the dynamic change of ... And Nodejs will this wonderful to language moved to the service side, wonderful to the wonderful, but from the heart said, they are very flexible, also more fun.

About Nodejs suitable io dense what I do not understand, but the feeling of getting started is relatively easy, I see the Tsinghua publishing to the node. JS Development of practical details (have to spit slot: This book is a lot of errors), two or three days to get started. Look at the next chapter, feel the difficulty behind will be increased, but all things are interlinked, he and other such as PHP or the like will have a lot of commonality.

Have to mention Jade (now called Pug) provided by the template engine, he put our beautiful HTML made that look really uncomfortable ah, in contrast, like Ejs this template engine, found that he JSP looks like Ah, like to meet an older friend.

Just getting Started Nodejs, about some of the mistakes and errors in the article also ask you to criticize the garden friends. Finally, if you like half blood, please pay attention to him.

Nodejs for an online form-filling application

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.