var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
Logs undefined
, why?
var content; fs. readFile('./Index. html', function read(err, data) { if (err) { throw err; } content = data; }); console.
To get the contents of a file as a string, we can use the readFileSync() or readFile() functions from the native filesystem ( fs ) module in Node. js. /* Get all the contents from a file */ const content = readFileSync("myFile. txt");
Syntax: fsPromises.readFile( path, options ) Parameters: The method accept two parameters as mentioned above and described below: path: It holds the name of the file to read or the entire path if stored at other location. It is a string, buffer, URL or a filename. options: It holds the encoding of file.
readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background.
To elaborate on what @Raynos said, the function you have defined is an asynchronous callback. It doesn't execute right away, rather it executes when the file loading has completed. When you call readFile, control is returned immediately and the next line of code is executed. So when you call console.log, your callback has not yet been invoked, and this content has not yet been set. Welcome to asynchronous programming.
Example approaches
const fs = require('fs'); // First I want to read the file fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } const content = data; // Invoke the next step here however you like console.log(content); // Put all of the code here (not the best solution) processFile(content); // Or put the next step in a function and invoke it }); function processFile(content) { console.log(content); }
Or better yet, as Raynos example shows, wrap your call in a function and pass in your own callbacks. (Apparently this is better practice) I think getting into the habit of wrapping your async calls in function that takes a callback will save you a lot of trouble and messy code.
function doSomething (callback) { // any async callback invokes callback with response } doSomething (function doSomethingAfter(err, result) { // process the async result });
There is actually a Synchronous function for this:
http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding
fs.readFile(filename, [encoding], [callback])
Asynchronously reads the entire contents of a file. Example:
fs.readFile('/etc/passwd', function (err, data) { if (err) throw err; console.log(data); });
The callback is passed two arguments (err, data), where data is the contents of the file.
If no encoding is specified, then the raw buffer is returned.
fs.readFileSync(filename, [encoding])
Synchronous version of fs.readFile. Returns the contents of the file named filename.
If encoding is specified then this function returns a string. Otherwise it returns a buffer.
var text = fs.readFileSync('test.md','utf8') console.log (text)
function readContent(callback) {
fs.readFile("./Index.html", function (err, content) {
if (err) return callback(err)
callback(null, content)
})
}
readContent(function (err, content) {
console.log(content)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With