使用 Node.js 從文字檔案讀取內容到陣列中


我們可以使用 Node.js 讀取文字檔案並將其內容作為陣列返回。我們可以使用此陣列內容處理其行或僅僅為了讀取。我們可以使用“fs”模組來處理檔案的讀取。fs.readFile() 和 fs.readFileSync() 方法用於讀取檔案。我們還可以使用此方法讀取較大的文字檔案。

示例(使用 readFileSync())

建立一個名為 fileToArray.js 的檔案,並複製以下程式碼片段。建立檔案後,使用以下命令執行此程式碼,如下面的示例所示:

node fileToArray.js

fileToArray.js

// Importing the fs module
let fs = require("fs")

// Intitializing the readFileLines with the file
const readFileLines = filename =>
   fs.readFileSync(filename)
   .toString('UTF8')
   .split('
'); // Calling the readFiles function with file name let arr = readFileLines('tutorialsPoint.txt'); // Printing the response array console.log(arr);

輸出

C:\home
ode>> node fileToArray.js [ 'Welcome to TutorialsPoint !',    'SIMPLY LEARNING', '' ]

示例(使用非同步 readFile())

我們來看另一個示例。

// Importing the fs module
var fs = require("fs")

// Intitializing the readFileLines with filename
fs.readFile('tutorialsPoint.txt', function(err, data) {
   if(err) throw err;
      var array = data.toString().split("
");    for(i in array) {       // Printing the response array       console.log(array[i]);    } });

輸出

C:\home
ode>> node fileToArray.js Welcome to TutorialsPoint ! SIMPLY LEARNING

更新於:20-May-2021

5K+ 瀏覽

啟動你的 職業

完成課程獲得認證

開始
廣告