2011-08-29 131 views

回答

6

試試這個:

var fs=require('fs'); 

fs.readFile('/path/to/file','utf8', function (err, data) { 
    if (err) throw err; 
    var arr=data.split('\n'); 
    arr.forEach(function(v){ 
    console.log(v); 
    }); 
}); 
0

有很多方法來讀取一個文件節點。您可以通過the Node documentation about the File System module, fs瞭解所有這些信息。

就你而言,假設你想讀取一個簡單的文本文件countries.txt,看起來像這樣;

Uruguay 
Chile 
Argentina 
New Zealand 

首先,你必須require()fs模塊在你的JavaScript文件的頂部,這樣的;

var fs = require('fs'); 

然後用它閱讀您的文件,你可以使用fs.readFile()方法,像這樣的;現在

fs.readFile('countries.txt','utf8', function (err, data) {}); 

,該{}裏面,你可以用readFile方法的結果進行交互。如果出現錯誤,結果將被存儲在err變量中,否則結果將被存儲在data變量中。您可以在這裏登錄data變量以查看您正在處理的內容;

fs.readFile('countries.txt','utf8', function (err, data) { 
    console.log(data); 
}); 

如果你這樣做了,你應該得到終端文本文件的確切內容;

Uruguay 
Chile 
Argentina 
New Zealand 

我認爲這就是你想要的。你的輸入被換行符分開(\n),並且輸出結果也會如此,因爲readFile不會更改文件的內容。如果需要,可以在記錄結果之前對文件進行更改;

fs.readFile('calendar.txt','utf8', function (err, data) { 
    // Split each line of the file into an array 
    var lines=data.split('\n'); 

    // Log each line separately, including a newline 
    lines.forEach(function(line){ 
    console.log(line, '\n'); 
    }); 
}); 

這將在每行之間添加一個額外的換行符;

Uruguay 

Chile 

Argentina 

New Zealand 

你也應該考慮,同時通過第一次訪問data前右加就行了if (err) throw err讀取文件所發生的任何可能的錯誤。你可以把所有的代碼放在一個叫做read.js的腳本中,像這樣;

var fs = require('fs'); 
fs.readFile('calendar.txt','utf8', function (err, data) { 
    if (err) throw err; 
    // Split each line of the file into an array 
    var lines=data.split('\n'); 

    // Log each line separately, including a newline 
    lines.forEach(function(line){ 
    console.log(line, '\n'); 
    }); 
}); 

然後,您可以在終端中運行該腳本。導航到包含countries.txtread.js的目錄,然後鍵入node read.js並按回車。您應該看到屏幕上顯示的結果。恭喜!你已經閱讀了Node的文件!