Like this article? We recommend
Using read()
Use the read() method to read file data. You must first use the open() method before attempting to read from the file. The read() method takes numerous arguments, but you should know that the read() method uses the file descriptor, obtained from the open() method, along with the file size (obtained from stats). An example appears below:
var fs = require("fs"); var path = "c:\\Temp\\Test.txt"; fs.stat(path, function(error, stats) { fs.open(path, "r", function(error, fd) { var buffer = new Buffer(stats.size); fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) { var data = buffer.toString("utf8"); console.log(data); }); }); });
The above code is fine if you need to position reading within a certain buffer size and position, but you usually want these details taken care of for you. You can use the readFile() method for this:
var fs = require("fs"); var path = "c:\\Temp\\Test.txt"; fs.readFile(path, "utf8", function(error, data) { if (error) { console.error("read error: " + error.message); } else { console.log(data); } });