在 JS (Node.js) 中读取 txt 文件的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16732166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:36:26 来源:igfitidea点击:
Read txt file's lines in JS (Node.js)
提问by JustLogin
I want to read a text file (.txt) using Node.js. I need to push each of text's lines into array, like this:
我想使用 Node.js 读取文本文件 (.txt)。我需要将每个文本行推入数组,如下所示:
a
b
c
to
到
var array = ['a', 'b', 'c'];
How can I do this?
我怎样才能做到这一点?
回答by Denys Séguret
You can do this :
你可以这样做 :
var fs = require("fs");
var array = fs.readFileSync(path).toString().split('\n');
Or the asynchronous variant :
或异步变体:
var fs = require("fs");
fs.readFile(path, function(err, f){
var array = f.toString().split('\n');
// use the array
});

