node 文本替換


 音樂分享:

Travis Scott - 《Drugs You Should Try It》

Travis Scott今年無論是單曲、球鞋市場、八卦戀情 熱度就沒停過,前兩天又出了廠牌聯合專輯《JACKBOYS》

最近翻到這首老歌還挺喜歡(歌詞聽聽算了。。。。)

——————————————————————————————————————————————————————————

項目地址:https://github.com/uustoboy/TxtReplace

項目介紹:node遍歷文件替換文本

核心邏輯:

遍歷文件夾

 1 const fs = require('fs')
 2 const path = require('path')
 3 const log4js = require('log4js')
 4 
 5 // log4js setting
 6 const logger = log4js.getLogger()
 7 logger.level = 'debug'
 8 
 9 // input your path
10 const inputPath = '/home/jialei/'
11 const filePath = path.resolve(inputPath)
12 
13 logger.debug(filePath)
14 
15 // test
16 fileDisplayPath(filePath)
17 
18 /**
19  * 文件遍歷
20  * @param fileDisplayPath
21  */
22 function fileDisplayPath (filePath) {
23     fs.readdir(filePath, (err, files) => {
24         if (err) {
25             logger.debug(err)
26         } else {
27             files.forEach ( (filename) => {
28                 // 獲取絕對路徑
29                 let filedir = path.join(filePath, filename)
30 
31                 fs.stat(filedir, (error, stats) => {
32                     if (error) {
33                         logger.debug(error)
34                     } else {
35                         // 文件夾、文件的不同處理
36                         let isFile = stats.isFile()
37                         let isDir = stats.isDirectory()
38 
39                         if (isFile) {
40                             logger.debug('filename is ~~', filedir)
41                         }
42 
43                         if (isDir) {
44                             // 遞歸
45                             fileDisplayPath(filedir)
46                         }
47                     }
48                 })
49             })
50         }
51     })
52 }
View Code

取出文本替換:

 1 var result = str.replace(/&|<|>|'|"/g, function(matchStr) {
 2     var tokenMap = {
 3         '&': '&amp;',
 4         '<': '&lt;',
 5         '>': '&gt;',
 6         "'": '&apos;',
 7         '"': '&quot;'
 8     };
 9     return tokenMap[matchStr];
10 });
11 
12 作者:張正誠
13 鏈接:https://www.zhihu.com/question/60796093/answer/189155578
14 來源:知乎
15 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
View Code

后記:

年末公司http轉https,之前老項目的css,js寫的絕對路徑逐個人工改的路徑

一天加班路上突然想到node替換,不過真實項目也就用node替換的css里的絕對路徑, js項目情況比較復雜還是人工替換的

參考資料:

賈磊 : 《node遍歷文件》

張正誠 : 《如何在JS中利用正則一次replace多個不同字符串?》

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM