Problem
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
Logs undefined, why?
Asked by karaxuna
Solution #1
To expand on @Raynos’ comment, the function you defined is an asynchronous callback. It doesn’t start running straight immediately; instead, it waits till the file loading is finished. Control is instantly returned and the following line of code is performed when you use readFile. So your callback hasn’t been called yet, and this content hasn’t been set yet when you call console.log. Hello, and welcome to the world of 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);
}
Better yet, wrap your call in a function and pass in your own callbacks, as Raynos demonstrates. (Apparently, this is a better approach.) I believe that wrapping your async calls in a function that accepts a callback will save you a lot of time and code.
function doSomething (callback) {
// any async callback invokes callback with response
}
doSomething (function doSomethingAfter(err, result) {
// process the async result
});
Answered by Matt Esch
Solution #2
This is anything for which there is a Synchronous function:
http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding
fs.readFile(filename, [encoding], [callback])
Asynchronously reads a file’s whole contents. Example:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
The callback is given two arguments (err, data), with data being the file’s contents.
The raw buffer is returned if no encoding is specified.
fs.readFileSync(filename, [encoding])
fs.readFile is a synchronous variant of fs.readFile. The contents of the file named filename are returned.
This function returns a string if encoding is given. Otherwise, a buffer is returned.
var text = fs.readFileSync('test.md','utf8')
console.log (text)
Answered by Logan
Solution #3
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)
})
Answered by Raynos
Solution #4
The mz module provides guaranteed versions of the node library’s core. It’s easy to use them. Install the library first…
npm install mz
Then…
const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
.catch(err => console.error(err));
You may also write them as asynchronous functions:
async function myReadfile () {
try {
const file = await fs.readFile('./Index.html');
}
catch (err) { console.error( err ) }
};
Answered by Evan Carroll
Solution #5
This line will be effective.
const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);
Answered by Aravin
Post is based on https://stackoverflow.com/questions/10058814/get-data-from-fs-readfile