Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

โหลดไฟล์ข้อความและค้นหาจำนวนอักขระในไฟล์ - JavaScript


สมมติว่าเรามีไฟล์ data.txt ที่อยู่ในไดเร็กทอรีเดียวกันกับไฟล์ NodeJS ของเรา สมมติว่าเนื้อหาของไฟล์นั้นเป็น −

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s.

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่โหลดไฟล์ข้อความภายนอกนี้ลงในไฟล์ js ของเราและส่งคืนจำนวนอักขระในไฟล์นี้

ตัวอย่าง

มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −

const fs = require('fs');
const requireFile = async () => {
   const data = fs.readFileSync('./data.txt', 'utf-8');
   const len = data.length;
   return len;
};
requireFile().then(res => console.log(res)).catch(err => {
   console.log('some error occured');
})

ผลลัพธ์

ผลลัพธ์ในคอนโซล:−

399