1. 来源
- 想对于自己接触前端日常学习与思考的代码行数进行一个统计,看自己大约敲了多少代码
2.代码
const fs = require('fs')
const path = require('path')
function calculateCodeLines ({ directory = '', writeResFilePath = '',
fileReg = /\.(js|ts|jsx|tsx|vue|html)$/, blckNameList = [], deleteComment = true },) {
let totalLines = 0
let fileList = {}
let fileCounts = 0
blckNameList = blckNameList.concat(['node_modules', '.lock'])
function traverseFolder (dir) {
const files = fs.readdirSync(dir)
for (const file of files) {
const filePath = path.join(dir, file)
const stats = fs.statSync(filePath)
if (blckNameList.some(item => filePath.includes(item))) {
continue
}
if (stats.isDirectory()) {
traverseFolder(filePath)
} else if (
stats.isFile() &&
fileReg.test(file) // 只计算指定扩展名的文件
) {
let code = fs.readFileSync(filePath, 'utf8')
// 是否去除注释
deleteComment && (code = code.replace(/\/\/(.*)/g, ''))
deleteComment && (code = code.replace(/\/\*[\s\S]*?\*\//g, ''))
// 统计行并且去除空行
const lines = code.split('\n').filter(line => line.trim() !== '').length
// 是否写入文件
writeResFilePath && (fileList[fileCounts + 1 + '==' + filePath] = lines)
// 累加代码行数
totalLines += lines
fileCounts++
}
}
}
traverseFolder(directory)
writeResFilePath && (() => {
fs.writeFile(writeResFilePath, JSON.stringify({ totalLines, fileCounts, fileList }, null, 2), { encoding: 'utf-8' }, (err) => {
if (err) {
console.log('文件写入错误', err) // zdz-log
}
})
})()
const res = { totalLines, fileCounts }
console.log(res) // zdz-log
return res
}
calculateCodeLines({
// 要统计的文件夹路径
directory: '/Users/zdz/Desktop/learn-code',
// 结果是否写入文件以及文件名称 结果为JSON字符串
writeResFilePath: '/Users/zdz/Desktop/learn-code/totalCode.json',
// 要统计哪些格式的文件
fileReg: /\.(js|ts|jsx|tsx|vue|html)$/,
// 要过滤哪些文件夹或者文件不算入统计 默认会忽略 'node_modules', '.lock'
blckNameList: ['slintrc', '11.source-code-read', 'React_Nativ', 'onfig.js', 'config/jest/', 'ackages/', 'ue_source/', 'e/08_vue3直播项目_project-admin'],
// 是否删除注释后统计
deleteComment: false,
})
package.json
{
"dependencies": {
"typescript": "^4.9.5"
},
"scripts": {
"lines":"node /Users/zdz/Desktop/learn-code/06.思考问题/02.js探索/26.统计代码行数.js"
},
"semi": false
}
3.结果