使用 nodejs 统计代码行数

本文介绍了如何利用 Node.js 编写脚本来统计代码文件的行数,包括具体的实现方法和步骤,帮助开发者提升代码管理效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

片段 - 万物皆片段(可能是最好用的代码分享平台)

let fs = require('fs')
let path = require('path')


// 获取命令行参数
let parm = process.argv.splice(2)
// 第一个参数是路径
let rootPath = parm[0]
// 后面的所有参数都是文件后缀
let types = parm.splice(1)
// 需要过滤的文件夹
let filter = ['./node_modules']
// 统计结果
let num = 0


// 获取行数
async function line(path) {
    let rep = await fs.readFileSync(path)
    rep = rep.toString()
    let lines = rep.split('\n')
    console.log(path + ' ' + lines.length)
    num += lines.length
}


// 递归所有文件夹统计
async function start(pt) {
    let files = fs.readdirSync(pt)
    files
        .map(file => {
            return `${pt}/${file}`
        })
        .forEach(file => {
            let stat = fs.statSync(file)
            if (stat.isDirectory()) {
                if (filter.indexOf(pt) != -1) {
                    return
                }
                start(file)
                return
            }
            let ext = path.extname(file)
            if (types.indexOf(ext) != -1) {
                line(file)
            }
        })
}


;(async () => {
    await start(rootPath)
    console.log(`总代码行数:${num}`)
})()

使用方法

// 统计当前文件夹下所有 .js .json 代码行数(相对路径)
node ./app.js . .js .json
// 统计 E:\pro\aliyun 目录下 .java .kt .xml .c 代码行数(绝对路径)
node ./app.js E:\pro\aliyun .java .kt .xml .c
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值