Node.JS枚举统计当前文件夹和子目录下所有代码文件行数
- 作者: 隔壁老王独霸后宫
- 来源: 51数据库
- 2021-08-16
使用node.js的大多数用记事本开发,有时侯会需要统计工程代码量,然后记事本大部分没有这个功能。其实用node.js几行代码就可以实现。
var path = require('path')
var fs = require('fs')
//需要统计的文件类型,可自己删减,均小写
var codesfiles = [ '.css', '.js', '.html', '.tmpl', '.part', '.json', '.md', '.txt', '.yml', '.java', '.cs', '.c', '.h', '.cpp', '.xml', '.go', '.py' ]
var lines = 0
var findfolder = function(srcdir, cb) {
fs.readdir(srcdir, function(err, files) {
var count = 0
var checkend = function() {
++count == files.length && cb && cb()
}
if (err) {
checkend()
return
}
files.foreach(function(file) {
var extname = path.extname(file).tolowercase()
var srcpath = path.join(srcdir, file)
fs.stat(srcpath, function(err, stats) {
if (stats.isdirectory()) {
findfolder(srcpath, checkend)
} else {
if (codesfiles.indexof(extname) < 0) {
checkend()
return
}
fs.readfile(srcpath, function(err, data) {
if (err) {
checkend()
return
}
var lines = data.tostring().split('\n')
lines += lines.length
console.log(srcpath, lines.length)
checkend()
})
}
})
})
//为空时直接回调
files.length === 0 && cb && cb()
})
}
findfolder('./', function() {
console.log('lines:', lines)
})
使用时将此脚本文件命名为lines.js,然后复制到需要统计的文件夹下,然后执行
node lines.js
然后会统计每一个代码文件的长度,和代码总行数:
$ node lines.js lines.js 56 package.json 6 local\en-us.js 122 local\fe.zh-cn.js 306 ... lines: 40464
更新
下面的脚本通过检测是否含有asc0的值来判断文件是不文本文件,然后统计代码行数,但实测统计数量明显偏多。
var path = require('path')
var fs = require('fs')
var lines = 0
var files = 0
//http://www.51sjk.com/Upload/Articles/1/0/268/268548_20210708023934144.js
function istextfile( filepath, length ) {
fd = fs.opensync( filepath, 'r' );
length = length || 1000;
for( var i = 0;i < length;i++ ) {
buf = new buffer( 1 );
var bytes = fs.readsync( fd, buf, 0, 1, i );
char = buf.tostring().charcodeat();
if ( bytes === 0) {
return true;
} else if(bytes === 1 && char === 0) {
return false;
}
}
return true;
}
var findfolder = function(srcdir, cb) {
fs.readdir(srcdir, function(err, files) {
var count = 0
var checkend = function() {
++count == files.length && cb && cb()
}
if (err) {
checkend()
return
}
files.foreach(function(file) {
var extname = path.extname(file).tolowercase()
var srcpath = path.join(srcdir, file)
fs.stat(srcpath, function(err, stats) {
if (stats.isdirectory()) {
findfolder(srcpath, checkend)
} else {
// if (codesfiles.indexof(extname) < 0) {
// checkend()
// return
// }
if (!istextfile(srcpath)) {
checkend()
return
}
fs.readfile(srcpath, function(err, data) {
if (err) {
checkend()
return
}
var lines = data.tostring().split('\n')
lines += lines.length
if (lines.length > 5000) {
console.trace(srcpath, lines.length)
} else {
console.log(srcpath, lines.length)
}
files++
checkend()
})
}
})
})
//为空时直接回调
files.length === 0 && cb && cb()
})
}
findfolder('./', function() {
console.log('lines:', lines)
console.log('files:', files)
})
总结
以上所述是小编给大家介绍的node.js枚举统计当前文件夹和子目录下所有代码文件行数,希望对大家有所帮助
推荐阅读
