Home > Article > Web Front-end > How to use nodejs to separate js and css in html files (code example)
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 = '<link rel="stylesheet" href="./test.css">'; let jsrc = '<script src="./test.js">'; let styleCollection, scriptColletion; let cssContent = '', jsContent = '', htmlContentStr = ''; 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,'').replace(/<\/style>/g, '').replace(/("")/g,'') for (let i =0;i<scriptColletion.length;i++) { jsContent += JSON.stringify(scriptColletion[i]); } jsContent = jsContent.replace(/<script>/g,'').replace(/<\/script>/g, '') .replace(/<\/script>"*<script>/g, '').replace(/("")/g,'') await appendFile('./test/test.css', JSON.parse(cssContent), 'css'); console.log('我应该是在---css写入成功---后出现!'); await appendFile('./test/test.js', JSON.parse(jsContent), 'js'); console.log('我应该是在---js写入成功---后出现!'); htmlContentStr = originContent .replace(allStyleReg, '') .replace(cssReg, cssLink) .replace(allScriptReg, '') .replace(jsReg, jsrc); console.log('copyTest.html 文本已经格式化,准备写入'); await writeHtml('./test/copyTest.html', htmlContentStr); console.log('==========================game-over============================='); })()</style></_files.length>
The code is really nothing good It’s explained, you’ll understand after reading it slowly. Run:
node extract-js-css
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
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!