載入文字檔案並在檔案中查詢字元數 - 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP