nodejs 编写一个计算代码行数的程序
时间: 2024-03-08 09:51:17 浏览: 20
好的,以下是一个基于 Node.js 的计算代码行数的程序示例:
```javascript
const fs = require('fs');
const path = require('path');
const countLines = (filePath) => {
return new Promise((resolve, reject) => {
let count = 0;
const readStream = fs.createReadStream(filePath);
readStream.on('data', (chunk) => {
count += chunk.toString('utf8')
.split(/\r\n|[\n\r\u0085\u2028\u2029]/g)
.length - 1;
});
readStream.on('end', () => {
resolve(count);
});
readStream.on('error', (err) => {
reject(err);
});
});
};
const countCodeLines = async (dirPath) => {
const files = fs.readdirSync(dirPath);
let count = 0;
for (const file of files) {
const filePath = path.join(dirPath, file);
if (fs.statSync(filePath).isDirectory()) {
count += await countCodeLines(filePath);
} else {
const extname = path.extname(filePath);
if (extname === '.js' || extname === '.ts' || extname === '.jsx' || extname === '.tsx') {
count += await countLines(filePath);
}
}
}
return count;
};
const dirPath = '/path/to/your/project';
countCodeLines(dirPath).then((count) => {
console.log(`Total code lines: ${count}`);
}).catch((err) => {
console.error(err);
});
```
这个程序会统计指定目录下所有 `.js`、`.ts`、`.jsx`、`.tsx` 文件中的代码行数,并输出总行数。你只需要将 `/path/to/your/project` 替换为你自己的项目路径即可。