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多个不同字符串?》

 

posted @ 2019-12-31 11:24  uustoboy  阅读(1271)  评论(0编辑  收藏  举报