JS General-like page refactoring what you can do with node. js

Source: Internet
Author: User
Tags readfile

First, non-computer background How to quickly learn about node. js?

The front-end should have listened to node. JS, the development background of children's shoes should have played.

For some without a computer background, the work content to the static page rendering of the front-end, may not have played with node. JS, and there is probably no more than a stereoscopic understanding of node. JS-Know this thing can run services, build a lot of front-end tools, look very strong look, but, This is probably the only possible limit.

"Can that few words summarize the myriad of node. js?" ”

Not ”

"What then?" ”

"Then six words and four languages!" ”

First, you know, node. js is a JavaScript runtime, and yes, it is used to run JavaScript. Previously JavaScript could only be Wang Wang in this small world of browsers. Many front-end small partners may be familiar with the JavaScript program language, other C + +,. NET and so on. In the past, if the browser woke up to extinction, many people would be unemployed. Just like a single species of food. Once this food is gone, it is a good idea to wait for extinction.

But, now, don't worry, node. js makes JavaScript an omnivorous, that is, in addition to Web behavior, you can build services, manipulate files, and so on, just like other languages like C + +.

We should all have used the. exe suffix file, double-click, you can lurk a virus or something; we may have used a. bat suffix batch file, one click, the picture in the folder is all renamed; so if it's a. js suffix file (assuming your system already has a node. JS environment installed), double-click ...... When you become a ... will open the editor to see the JS code, double-click is no use!

We can open the command line tool, CD to the specified directory, and then enter (assuming the JS file is named Test.js):

Node test

Then the code inside the Test.js can run merrily up and down!

For "page Aberdeen", it is enough to know so much!

    1. Post-installation node. JS Environment;

    2. Use our crappy JS to write a crappy processing of. js files;

    3. Node executes under.

In a simple trilogy, we become a front-end practitioner with a taste for development.

Second, the crappy JS of the first experience of node. js

The large number of factory are small factories, most of the small factories have only one front end, a lot of front-end JS is generally like.

Circles often put "front-end solution" on the tip of the mouth, in fact, there are front-end team, because there is a team, can be valuable.

"Front-end solution" is good, but, if you really care about the industry, you should know that can play in a large team is actually a small number of people, a lot of small partners are alone, this set of things may hinder the agility and flexibility; there are a lot of small partners in the 234-line city, Is the wild front-end development, the foundation is not enough, this set of complex things difficult to control, there are many many projects is a number of static activities page, there is no need to use anti-aircraft guns to fight mosquitoes.

At this point, it is often necessary to customize a very strong small and beautiful processing. Some students may be suspicious, ah, I JS level comparison dishes, self-made tools such things will be a bit burden ah. In fact, even if you JS, using node. js to build some gadgets to improve your front-end development efficiency is nothing.

Front of this thing, there is a bolt all agree with the characteristics, is to get started quickly!

First, we need a copy of the node. JS API document, we use "animal search" to search:

Just the first one, enter the list of APIs that will see a long line of content:

Don't be afraid, we just need this one, yes, just a file system (FS)! Others do not need to tube, those are played by senior players:

Click to go, again voluminous, a bunch of APIs:

Don't be afraid, we just need ... Calm, not A, is a number of regular additions and deletions read and write rename files can be.

Okay, and then just a little bit of a crappy JS, we can play it up.

What do you play? Let me see a set of anime think about ...

Designer to rename the icon

The industrious designer sent the small picture material of the fragrant Bobo, however, the connection character is the underline _, happens, at this time, the front-end child shoe's maiden disease sends the mistake, other oneself handles the picture all is the short horizontal line-the connection, here the icon all is the underline unbearable, wants all to replace with the short line, how to do?

If on the one or two icons OK, big deal manual change, but, if, as above, the designer gave 57 icons, I go, to change to scalp numbness Bar ~ is not a matter of time, but the repetition of the work brought by the kind of boring and unpleasant will affect the passion of the job, and this kind of labor has not been used, can not be reused, And not as a result (I can rename 100 files in 5 minutes, there is an egg ~).

At this point, node. JS can be unveiled, with the node. JS Environment, we just a few lines of JS code, we can completely kill, very simple, read all the pictures in the folder, and then the name of all the underscore _ replaced by a dash-, Suppose our. js file and the small icon folder that needs to be processed are structured as follows:

Underscore2dash.js content is as follows:

Introducing FS File Processing module

var fs = require("FS");

Now what we're going to care about is the ' icons ' folder

We might as well use variables to represent this folder name to facilitate future maintenance and management

var src = ' icons ';

The API for traversing folders is found in the API documentation

Found, Fs.readdir (path, callback)

The document has a description:

Reads the contents of the directory that contains the path path. The callback function (callback) accepts two parameters (err, files) where files is an array of file names contained in a storage directory

So:

FS. Readdir(src, function(err, files) {

//files is an array of names, so

//can use foreach traversal ha, here is ES5 js a bit of knowledge

//If not clear, you can also use the For loop, ha

files. ForEach(function(filename) {

//Below is the file name rename

The renamed API is found in the//API documentation as follows

//Fs.rename (OldPath, NewPath, callback)

//below, we can draw the gourd to determine the new and old file name:

var oldpath = src + '/' + filename, newpath = src + '/' + filename. Replace(/_/g, '-');

//Rename walk

FS. Rename(oldpath, newpath, function(err) {

if (! Err) {

console. Log(filename + ' underline replaced successfully! ') );

}      

})

});

});

Window System example, we use CMD or PowerShell, in the corresponding folder directory under the execution of the JS file:

Node Underscore2dash

Results:

Picture of the folder at this time:

The file name batch substitution here applies not only to pictures, but to files in any format.

Currently, the batch processing of the named is more than the same, including the uniform prefix (for example, icon_*), as long as the NewPath = post-full code is changed to SRC + '/icon_ ' + filename. or non-development needs, such as the bulk download of the small video name from 1 to the back row, then ... Do it yourself, the second parameter of the Foreach method is the array ordinal value, you can use it directly, when the homework after class, watch you Yo!

This folder batch processing examples, aside from detailed comments, almost 10 lines of JS code, the use of the JS method is very very basic, right, array traversal foreach and character replacement replace method, the other is set API walk routines, even if my wife (non-it field) personally, You can also get it out. Simple, and interesting.

I strongly recommend that the University's program development introductory course learn JavaScript, run Web pages, run node. js, simple and WYSIWYG, easy to stimulate the fun of learning, more than boring do not know what to use C language more suitable for popular science and the introduction.

Third, the crappy JS under the first experience of node. JS two weeks

We write page actual development requirements certainly do not know the file batch rename so simple, I know there is a demand point, especially often write static prototype page of small partners must be interested.

That is, HTML pages can also be used as dynamic languages, such as PHP, and each module is included directly. Now there is a common problem, a project, refactoring staff to write more than 20 static pages, but, because HTML can not directly include the common head of the bottom and the sidebar, resulting in the 20 pages of the head and tail are independent, general header content has changed, hehe, I guess we'll have to ask the editor for a batch replacement.

Is this a pain point? Obviously it is! Pain points in all things can make a contribution to reflect their own value of the place.

Yes, we work is the page, our JS can barely help the wall, but, that is, as long as you have this heart, aware of the problem, but also know that node. JS can do this for you, a practical tool has actually finished half. Refer to the API documentation, the east to fight, the west to gather together, certainly can make a at least oneself uses very high thing, the remaining half is so simple continuation.

Examples of examples indicate

There is an original HTML page that uses a standard HTML5 import that resembles the following code:

<link rel="import" href="header.html"/>

However, in fact, rel= "import" and include are completely different concepts, import comes in is actually a separate document! But this is something, anyway we are not directly browsing this page, therefore, you do not have to care about this detail.

HTML several file structure relationships are as follows:

At this point, we can use node. js and our little JS knowledge to replace the rel= "import" html with the corresponding imported HTML page content.

The principle is actually very simple:

    1. Read Import-example.html page;

    2. href= "header.html" This line of HTML to replace the contents of header.html;

    3. Monitoring Import-example.html page, a change, instant generation;

    4. done!

The following is the JS code for this example import.js:

Introducing FS File Processing module

var fs = require("FS");

The HTML page folder address and file name for the test

var src = ' import ', filename = ' import-example.html ';

var fnimportexample = function(src, filename) {

//Read HTML page data

//using fs.readfile (filename, [options], callback) in the API documentation

FS. ReadFile(src + '/' + filename, {

//need to specify encoding, otherwise return to native buffer

encoding: ' UTF8 '

}, function(err, data) {

//The next thing to do is to

//

//This HTML is replaced with the contents of the href file

//Can ask for universal regular

var datareplace = data. Replace(//gi, function (MATCHS, M1) {

//M1 is the matching path address.

//Then you can read the file.

return FS. Readfilesync(src + '/' + M1, {

encoding: ' UTF8 '

});

});

//Because we want to put the file in a higher level directory, so some relative address to be processed under

//In this case, it is relatively simple, yes. /To replace

datareplace = datareplace. Replace(/"... G, ' "');

Then a new HTML file is generated

Document Find Fs.writefile (filename, data, [options], callback)

Fs.writefile (filename, datareplace, {

Encoding: 'UTF8'

}, function (err) {

if (err) throw err;

Console.log (filename + ' build succeeded! ');

});

});

};

The default is first executed once

Fnimportexample (src, filename);

Monitor file, regenerate after change

Fs.watch (src + '/' + filename, function (event, filename) {

if (event = = ' Change') {

Console.log (src + '/' + filename + ' has changed, regenerated ... ');

fnimportexample(src, filename);

}

});

We now node run:

Node Import

Results:

The folder at this time:

The arrow refers to the newly generated HTML page, at which point the content is:

We visit this page:

Even the ads are showing good!

At this point, node is actually the Fs.watch () method in the document that monitors whether the original HTML has changed, for example, if we change the mm1 of the image address to mm2, then:

At this point the page becomes:

Thus, a prototype of a gadget that automatically compiles imports to import HTML pages at any time is fine.

Page refactoring of the small partners, do not worry about more than 20 prototype page common part of the change to change more than 20 problems, directly import the common module, more than 20 pages compiled into HTML page full body.

Now, let's look back at the gadget introduced by the HTML support module above, which is a few simple node. JS APIs and a few lines of simple JS. We are not open source for their own use, a lot of complex scenes are not to consider, so, so simple is enough!

Iv. concluding remarks

When the project is relatively small, when the team members are less, when the development of the students do not bird you, at this time, to carry forward their own hands, the spirit of the clothed.

When developing a pain point, or feeling like you're doing repetitive work, think about whether you can spend some time churn out a small script for node. js.

Don't assume that the tools in the NPM repository seem diao and hard to do, in fact, a little bit of the core plus a variety of scenarios to get out. As we are entertaining, the pursuit of agile and efficient, focused on the immediate task function, so we just get the core out of the good, and these cores are often a few lines of JS code + several FS API can be.

Although the ants are small, biting people also hurts. So, do not feel yourself js comparison dish, do not come, just a few lines of JS code, you do not have to engage in how do you make sure?

CSS-based front-end want to develop, there is no better than the introduction of this article is more suitable for learning and getting started.

JS General-like page refactoring what to do with node. JS (Go)

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.