返回一个数组,数组中每个元素是指定文件中的每一行。
在 fs
node 包中使用 readFileSync
函数指定文件中创建一个 Buffer
。使用 toString(encoding)
函数将 buffer 转换为字符串。通过逐行 split
文件内容(每个\n
)根据文件内容创建一个数组。
const fs = require('fs'); const readFileLines = filename => fs .readFileSync(filename) .toString('UTF8') .split('\n');
/* contents of test.txt : line1 line2 line3 ___________________________ */ let arr = readFileLines('test.txt'); console.log(arr); // ['line1', 'line2', 'line3']
更多代码 JavaScript 实用代码片段 请查看 https://www.html.cn/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂