将本地文本文件读入 JavaScript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34857458/
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-08-23 16:57:53  来源:igfitidea点击:

Reading local text file into a JavaScript array

javascripttext

提问by William Ross

I have a text file in the same folder as my JavaScript file. Both files are stored on my local machine. The .txt file is one word on each line like:

我在与 JavaScript 文件相同的文件夹中有一个文本文件。这两个文件都存储在我的本地机器上。.txt 文件每行一个字,如:

red 
green
blue
black

I want to read in each line and store them in a JavaScript array as efficiently as possible. How do you do this?

我想读取每一行并将它们尽可能高效地存储在 JavaScript 数组中。你怎么做到这一点?

回答by siavolt

Using Node.js

使用 Node.js

sync mode:

同步模式:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

异步模式:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

更新

As of at least Node 6, readFileSyncreturns a Buffer, so it must first be converted to a string in order for splitto work:

至少从 Node 6 开始,readFileSync返回 a Buffer,因此必须首先将其转换为字符串才能split工作:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

或者

var text = fs.readFileSync("./mytext.txt", "utf-8");