加载文本文件并在文件中查找字符数 - 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

更新于: 15-9-2020

1000+ 次浏览

开拓您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.