加载文本文件并查找文件中的字符数 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/5 9:48:17
假设我们有一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

