ใช้โมดูล fs (File System) ของ Node.js อ่านไฟล์ข้อความ แล้วนับความยาว (จำนวนตัวอักษร)
ตัวอย่างโค้ด
const fs = require('fs');
const requireFile = async () => {
const data = fs.readFileSync('./data.txt', 'utf-8');
return data.length;
};
requireFile()
.then(res => console.log(res))
.catch(err => console.log('some error occured'));
ผลลัพธ์
399
วิธีแบบ Async (แนะนำสำหรับ Production)
const fs = require('fs').promises;
const countChars = async (filepath) => {
try {
const data = await fs.readFile(filepath, 'utf-8');
return data.length;
} catch (err) {
console.error('Error reading file:', err);
return 0;
}
};
countChars('./data.txt').then(console.log);
วิธีนับเฉพาะตัวอักษร (ไม่นับ whitespace)
const countCharsNoSpace = async (filepath) => {
const data = await fs.readFile(filepath, 'utf-8');
return data.replace(/\s/g, '').length;
};