Computer >> Máy Tính >  >> Lập trình >> Javascript

Tải tệp văn bản và tìm số ký tự trong tệp - JavaScript

Giả sử chúng ta có tệp data.txt nằm trong cùng thư mục với tệp NodeJS của chúng ta. Giả sử nội dung của tệp đó là -

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.

Chúng tôi được yêu cầu viết một hàm JavaScript để tải tệp văn bản bên ngoài này vào tệp js của chúng tôi và trả về số ký tự trong tệp này.

Ví dụ

Hãy viết mã cho chức năng này -

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');
})

Đầu ra

Đầu ra trong bảng điều khiển:-

399