Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from fs.readFile

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

Logs undefined, why?

like image 808
karaxuna Avatar asked Apr 07 '12 22:04

karaxuna


People also ask

How do I get data from fs readFile?

var content; fs. readFile('./Index. html', function read(err, data) { if (err) { throw err; } content = data; }); console.

How do I read the content of a node js file?

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");

What Is syntax of readFile () method?

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.

What is the difference between fs readFile and fs readFileSync?

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.


3 Answers

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 }); 
like image 89
Matt Esch Avatar answered Sep 27 '22 20:09

Matt Esch


There is actually a Synchronous function for this:

http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding

Asynchronous

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.


SYNCHRONOUS

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) 
like image 38
Logan Avatar answered Sep 27 '22 19:09

Logan


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)
})
like image 36
Raynos Avatar answered Sep 27 '22 20:09

Raynos