Home > Web Front-end > JS Tutorial > body text

How to use nodejs to separate js and css in html files (code example)

不言
Release: 2019-04-11 14:03:20
forward
2056 people have browsed it

The content of this article is about how to use nodejs to separate js and css in html files (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Abstract: The content to be implemented in this article is to use nodejs to add, delete, modify and check files. The demonstration example-》Separate the content of script and style in an html file, and then generate js files and css files separately. . Intermediate processing of asynchronous api-》async/await, Promise

Project hosting: extract-js-css, welcome star

to directly upload the code:

// extract-js-css
// import fs from 'fs'
var fs = require('fs')
// import csscomb from 'csscomb'
// var csscomb = require('csscomb')
// var comb = new csscomb('zen');
// console.log(comb)

// 删除文件
const deleteFile = (path)=>{
    return new Promise(resolve => {
        fs.unlink(path, (err) => {
            if (err) {
                console.log(err)
                return
            };
            console.log(`已成功删除 ${path}文件`);
            resolve()
        });
    })
}

// 删除文件夹
const deleteDir = async (path)=>{
    let  _files =  await new Promise (resolve => {
        fs.readdir(path, (err,files) => {
            if (err) {
                console.log(err)
            };
            console.log(`已成功读取 ${path} 文件夹`);
            resolve(files)
        })
    })

    if(_files && _files.length) {
        for(let i =0;i<_files.length> {
        fs.rmdir(path, (err) => {
            if (err) {
                console.log(err)
            };
            console.log(`已成功删除空 ${path}文件夹`);
            resolve()
        })
    });
}
const emptyDir = (path) => {
    return new Promise(resolve => {
        fs.rmdir(path, (err) => {
            if (err) {
                console.log(err)
            };
            console.log(`已成功删除空 ${path}文件夹`);
            resolve()
        })
    })
}
// 新建文件夹
/**
 *  
 */
const mkdirTest = ()=>{
    return new Promise(resolve => {
        fs.mkdir('./test', { recursive: true }, (err, data)=>{
            if (err) {
                console.log(err)
            };
            console.log('新建文件夹成功')
            resolve()
        })
    })
}

// 读取html 内容
/**
 * 
 */
const readHtml = ()=>{
    return new Promise(resolve => {
        fs.readFile('./test.html', 'utf-8', (err, data)=>{
            if(err) {
                throw Error(err)
            }
            console.log('test.html 读取成功!--NO1')
            resolve(data)
        })
    })
}

// 写入css 和js
/**
 * 向文件中追加内容
 * @param {是文件名字} path 
 * @param {写入文件的内容} data 
 * @param {文件类型} type 
 * @author erlinger
 * @time 
 */
const appendFile = (path, data, type) => {
    return new Promise(resolve => {
        fs.appendFile(path, data, (err) => {
            if (err) {
                console.log(err)
            };
            console.log(`${type}数据已追加到文件`);
            resolve()
        });
    })
}
// 写一个html
const writeHtml = (path, data) => {
    return new Promise(resolve => {
        fs.writeFile(path, data, (err) =>{
            if(err) {
                console.log('err', err)
                return
            }
            console.log(`${path} 写入成功,功能结束!`);
            resolve() // 必须resolve 。不然 promise 就到此为止,调用该方法后面的代码将不执行
        })
    })
}

// 插件 方法入口
(async ()=>{
    console.log('==========================game-start=============================');
    await deleteDir('./test');
    console.log('我应该是等---删除文件夹后---才出现')

    await mkdirTest();
    console.log('我应该是在---文件夹新建成功---后出现!');

    let cssReg = /<style>[\s|\S]*?<\/style>/ig;
    let jsReg = /<script>[\s|\S]*?<\/script>/ig;
    let allStyleReg = /<\/style>[\s|\S]*?<style>/ig;
    let allScriptReg = /<\/script>[\s|\S]*?<script>/ig;
    let cssLink = &#39;<link rel="stylesheet" href="./test.css">&#39;;
    let jsrc = &#39;<script src="./test.js">&#39;;
    let styleCollection, scriptColletion;
    let cssContent = &#39;&#39;, jsContent = &#39;&#39;, htmlContentStr = &#39;&#39;;

    let originContent = await readHtml();
    styleCollection = originContent.match(cssReg);
    scriptColletion = originContent.match(jsReg);
    
    // 处理 css
    for (let i =0;i<styleCollection.length;i++) {
        cssContent += JSON.stringify(styleCollection[i]);
    }

    cssContent = cssContent.replace(/<style>/g,&#39;&#39;).replace(/<\/style>/g, &#39;&#39;).replace(/("")/g,&#39;&#39;)
    
    for (let i =0;i<scriptColletion.length;i++) {
        jsContent += JSON.stringify(scriptColletion[i]);
    }
    
    jsContent = jsContent.replace(/<script>/g,&#39;&#39;).replace(/<\/script>/g, &#39;&#39;)
    .replace(/<\/script>"*<script>/g, &#39;&#39;).replace(/("")/g,&#39;&#39;)
    
    await appendFile(&#39;./test/test.css&#39;, JSON.parse(cssContent), &#39;css&#39;);
    console.log(&#39;我应该是在---css写入成功---后出现!&#39;);

    await appendFile(&#39;./test/test.js&#39;, JSON.parse(jsContent), &#39;js&#39;);
    console.log(&#39;我应该是在---js写入成功---后出现!&#39;);

    htmlContentStr = originContent
    .replace(allStyleReg, &#39;&#39;)
    .replace(cssReg, cssLink)
    .replace(allScriptReg, &#39;&#39;)
    .replace(jsReg, jsrc);
    console.log(&#39;copyTest.html 文本已经格式化,准备写入&#39;);
    await writeHtml(&#39;./test/copyTest.html&#39;, htmlContentStr);

    console.log(&#39;==========================game-over=============================&#39;);
})()</style></_files.length>
Copy after login

The code is really nothing good It’s explained, you’ll understand after reading it slowly. Run:

node extract-js-css
Copy after login

If you want to use the es6 module, use the import import method, you need to install a separate babel, use this package to compile into es5, and run it. For specific use, you can down the project and run it.
For this project, the following needs to be reminded:

The processing of files is all asynchronous operations. If it is a single asynchronous operation method (for example: appendFile method), it is to asynchronously add content to the file. , directly encapsulate it into a promise, and then return it.

If an operation contains multiple asynchronous processing logic, you need to use async to declare the method, use await to wait for the asynchronous operation, and finally return a promise

before executing the main process , we use the method declared by async to call (I call the anonymous function directly), and use await to wait for the asynchronous operation, so that our main process is a synchronous execution process, which looks very refreshing.

The API method for asynchronous file operation in this article is asynchronous. The nodejs development documentation provides synchronous operation documentation. You can use the synchronous API directly. My main focus here is to use the async/await promise method during asynchronous operations to better grasp it.

A demo in the article provides a solution for processing multiple asynchronous operations, one asynchronous operation contains multiple asynchronous operations, including executing asynchronous operations in a loop, which specifically targets string processing of HTML files. , compared with rub, it is relatively simple when using regular matching and string formatting and parsing strings. After reading the file content, JSON.stringify is required, and later when filling in the file, JSON.parse is required. Currently, no suitable method has been found. If anyone has a suitable method, please let me know and we can communicate together. .

The following is a process of executing a main async method

How to use nodejs to separate js and css in html files (code example)

The above is the detailed content of How to use nodejs to separate js and css in html files (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!