Using Socket.io+fs.watchfile to automatically preview HTML on your browser

Source: Internet
Author: User
Tags emit readfile

As a front-end code Farm I spend one-third of the time on the F5, of course, I can also use runjs.cn such as online editor to preview my page in time, but the online editor smart tips and other functions far from the local editor easy to use Ah, there are classmates said, we can be used DW code/design mode, But I don't like DW (no reason not to like O (∩_∩) o)

Now there is a question to be sure that we want to use the local editor Vscode sublime What the love with what, then how to let the browser automatically refresh it, at first I think of artificial simulation F5. But there's a downside:

First, I don't write browser plugins.

Second, is not every browser to write a set of plugins AH ie chrome ff ... my God

The invention of the aircraft tells us that human beings are not to be flown by simulating birds shaking their wings. What else can be achieved by automatic page refresh ...

The moment of trouble stems from a deep concept can not extricate themselves, I need to refresh the browser, no, I need only the browser can update DOM.....DOM!!!!

Dom... Realtime...dom ... Realtime ....!!!

Well, I thought about Socket.io.

---------------------------------------------------above as background----------------------------------------------------------------- -------------

First explain how it works:

Use Fs.watchfile to detect if an HTML file changes (the change is triggered when we ctr+s the editor)

Send HTML file text to and from client after triggering change

Updates the DOM after the client receives the HTML file text

PS: They communicate through WebSocket (why use WebSocket, because I think WebSocket embodies the front-end personnel of NB expenditure ...)

Then there is the problem of how the client should build

At first I was going to use a div to render the HTML text that the server passed back.

However, there are the following issues

How to prevent CSS JS pollution

So use the IFRAME (IFRAME does not always need a src when working)

--------------------------------------------Code Practice---------------------------

First installs the Nodejs+socket.io (this does not have nonsense) please everybody own Baidu how installs

My installation experience is also very dog blood dare not unauthorized guidance

Official commencement:

Create App.js

var app=require (' http '). Createserver (Handler), Io=require (' Socket.io '). Listen (APP), Fs=require (' FS '), App.listen ( 8080); function handler (req,res) {fs.readfile (__dirname+ '/sandbox.html ', function (err,data) {if (err) {Res.writehead ( Return Res.end (' Error loading sandbox.html ');} Res.writehead (+); res.end (data);})} Io.sockets.on (' Connection ', function (socket) {fs.watchfile (__dirname+ '/test.html ', {persistent:true, interval:300} , function (status) {            if (status) {Console.log (status);} Fs.readfile (__dirname+ "/test.html", function (err,data) {     if (err) {Console.log (err); return false;} var str=data.tostring (); Socket.emit ("Render", str);});

App.js Code Interpretation:

First we create a HttpHandler (as ASP.) Listening on port 8080 defaults to native Locahhost, Io,fs are Socket.io and FS references respectively.

In handler we read the sandbox page of the current folder (there is an IFRAME in the sandbox page to preview, there will be detailed code below, note that the __dirname here refers to the current app.js in the path __ is two consecutive _)

The next step is to build a connection that you know

When the connection is established, we start watchfile

Now we only wath a file name test.html

Fs.wathfile is the FS module self-Implementation method The first parameter is the path of watch, the second is watch's interval, and the third is the response when the file changes

The following code simply reads the test.html text and sends it to the client via Socket.emit

Sandbox code:

<HTML>    <Head>        <Scripttype= "Text/javascript"src= "Socket.io/socket.io.js"></Script>        <Scripttype= "Text/javascript"src= "Http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></Script>        </Head>    <Body>            <iframestyle= "height:100%;width:100%;margin:0px;border:0px;"ID= "Prebox">                <Body>                                    </Body>            </iframe>        <Scripttype= "Text/javascript">          varPort="http://locahhost:8080/"              varSocket=Io.connect (port); Socket.on ('Render',function(data) {$ ("#prebox")[0].contentdocument.documentelement.innerhtml=data.replace ("</Script>    </Body></HTML>

Reference Socket.io.js (where is this file?) This file is actually quoted in the Socket.io when the node_modules, although I did not find, but I do understand that)

Refer to jquery (why this high version, because of the use of the Baidu Cdn Ah, in fact, a random version of jquery will be OK)

Creating a link to the socket is just a matter of updating the IFRAME when the server socket returns to the render event.

Test Browser for Chrome

Now open http://localhost:8080/you'll only see a blank

Then you update the code in test.html, you will find that the browser code is in real-time update ... I'm excited.

About the following questions .....

How about 1.socket performance?

2.watchFile Stable No

3. Is there any other framework to implement AH, you're a little bit like a hick.

4.test.html Path Why write dead, can't you be more flexible?

5. Write the code for this crap. Have you ever touched Nodejs?

6. Is it necessary to use a long connection such as a socket?

7. The layout of this article is too ugly, brother Taiwan you this typesetting is I have seen the ugliest.

I'll answer it myself.

1.socket performance is good (I haven't tested it)

2.watchFile Stable not (unstable, this I have tested, but does not hinder normal execution)

3. Someone has developed a plugin that automatically refreshes the F5, but does the programmer like to build the wheel?

4. For the clarity of the code readable (also can be understood as lazy)

5. Contacted only last week

6. Play your Own game

7. The second Blog Park article, the first article is about how the front-end form write verification framework is cursed very miserable (the theory describes the general I saved, thought can continue to write results many people are to come to see the code, scold me the title party, later I put the code, also did not see kua my, later deleted)

Using Socket.io+fs.watchfile to automatically preview HTML on your browser

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.