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

Logs undefined, why?

karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • 2
    fs.readFileSync also has cool features to read a file even if its in the unicode utf8 format. – Praneeth May 10 '17 at 23:37
  • N.B. fs.readFile can also do that ^ see my answer below – Dominic Dec 17 '18 at 14:55
  • Duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – E_net4 Nov 01 '22 at 19:10

17 Answers17

398

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
});
widged
  • 2,749
  • 21
  • 25
Matt Esch
  • 22,661
  • 8
  • 53
  • 51
  • 2
    Sync I/O has its place — it's fine if you're doing a small build system or tool. On larger systems or server apps best practice is to avoid it. – RobW May 26 '14 at 03:11
  • 40
    Not everything is a web server. And there's nothing horrible about horrible about using sync versions of methods for one-shot calls before the server has started taking requests. Anyone using Node should really understand why before using it. Definitely before rant-blogging about it. – Erik Reppen Mar 02 '15 at 22:42
  • For an example on [how to use promises to write asynchronous code in a simple synchronous fashion see my answer](http://stackoverflow.com/a/37516862/124486) – Evan Carroll May 30 '16 at 23:57
  • 14
    You have to include `'utf8'` after the filename as an additional parameter, otherwise it will just return a buffer. See : https://stackoverflow.com/questions/9168737/read-a-text-file-using-node-js – DollarAkshay Feb 12 '19 at 11:01
313

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)
Community
  • 1
  • 1
Logan
  • 10,649
  • 13
  • 41
  • 54
  • Quick question, what is the use of the buffer that is being returned in synchronous version of readFile? If i read a file synchronously and do not pass any encoding, it prints buffer, how can i use this? Thank you. – codingbbq Jul 21 '13 at 07:01
  • 14
    I had experience with this recently. Let's say our buffer is `data`. `if (Buffer.isBuffer( data){ result = data.toString('utf8'); }` Now we have converted the buffer into readable text. This is good for reading a plaintext file or testing the file against format types. I could do a try/catch to see if it's a JSON file for example; but only after buffer is converted to text. Look here for more information: http://nodejs.org/api/buffer.html – Logan Jul 22 '13 at 00:49
  • Also as far as I know buffers are octet streams, and good for sending data "piece by piece." You must have seen that the buffer is something like `AF 42 F1`. Very practical for client-server-client communication. – Logan Jul 22 '13 at 00:52
  • You are missing the `import` of `fs`. It should be [fs.promises](https://stackoverflow.com/a/56821924/1705829). – Timo Feb 09 '23 at 20:37
  • @Logan is using the version with callback-based asynchrony instead of promise-based asynchrony. – uzluisf May 18 '23 at 19:58
125
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)
})
Raynos
  • 166,823
  • 56
  • 351
  • 396
  • Hi, in the first line of your code, `function readContent(callback)`, is `callback` a reserved word? I mean, is this the standard way to implement callbacks for your custom functions? I've just started learning node. – Amal Antony Jul 22 '13 at 08:26
  • 3
    Hi Amal. Callback is simply the argument passed to his function, it could be `event` or `c` or any name you like - it is not a reserved word in Javascript, and I would assume the same extends to Node.js. – RealDeal_EE'18 Nov 25 '13 at 01:08
  • `readContent(function (err, content)` gives me a syntax error when using the function as a parameter. – monsto Nov 26 '15 at 17:16
76

Using Promises with ES7

Asynchronous use with mz/fs

The mz module provides promisified versions of the core node library. Using them is simple. First install the library...

npm install mz

Then...

const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
  .catch(err => console.error(err));

Alternatively you can write them in asynchronous functions:

async function myReadfile () {
  try {
    const file = await fs.readFile('./Index.html');
  }
  catch (err) { console.error( err ) }
};
Bruiser
  • 11,767
  • 5
  • 34
  • 45
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
28

This line will work,

const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);
Aravin
  • 6,605
  • 5
  • 42
  • 58
  • 1
    7 years passed :) `fs.readFileSync` is sync method, so no need for `await` there. Await is useful with promises (https://nodejs.org/api/fs.html#fs_fs_promises_api), when you want to write async code with syntax similar to sync code. – karaxuna Jan 08 '19 at 16:39
  • @karaxuna, yeah. removed. I just come across this case today & I resolved using above code. – Aravin Jan 08 '19 at 16:58
  • 1
    This is the simplest answer. If you don't need async, why in the world would you mix with the async version at all, with callbacks, async/await, etc?. This is the way to go. – Master of Ducks May 04 '20 at 12:19
24
var data = fs.readFileSync('tmp/reltioconfig.json','utf8');

use this for calling a file synchronously, without encoding its showing output as a buffer.

royhowie
  • 11,075
  • 14
  • 50
  • 67
user2266928
  • 465
  • 4
  • 3
14

As said, fs.readFile is an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);.

It's like sending some part of your code for a long trip (like reading a big file).

Take a look at the comments that I've written:

var content;

// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});

// in the meantime, please continue and run this console.log
console.log(content);

That's why content is still empty when you log it. node has not yet retrieved the file's content.

This could be resolved by moving console.log(content) inside the callback function, right after content = data;. This way you will see the log when node is done reading the file and after content gets a value.

rgettman
  • 176,041
  • 30
  • 275
  • 357
Taitu-lism
  • 856
  • 9
  • 10
13

From Node v8

Use the built in promisify library to make these old callback functions more elegant.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

async function doStuff() {
  try {
    const content = await readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}

From Node v10

You can use the promises version of fs API:

import { promises as fs } from 'fs';

async function doStuff() {
  try {
    const content = await fs.readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • Can be in single line `const doStuff = async (filePath) => fs.readFileSync(filePath, 'utf8');`, no need of util.promisify wrap. – rab Sep 16 '19 at 07:44
  • 2
    Not using the sync version is the point of this, and you should handle errors on calling it – Dominic Sep 17 '19 at 20:43
12
const fs = require('fs')
function readDemo1(file1) {
    return new Promise(function (resolve, reject) {
        fs.readFile(file1, 'utf8', function (err, dataDemo1) {
            if (err)
                reject(err);
            else
                resolve(dataDemo1);
        });
    });
}
async function copyFile() {

    try {
        let dataDemo1 = await readDemo1('url')
        dataDemo1 += '\n' +  await readDemo1('url')

        await writeDemo2(dataDemo1)
        console.log(dataDemo1)
    } catch (error) {
        console.error(error);
    }
}
copyFile();

function writeDemo2(dataDemo1) {
    return new Promise(function(resolve, reject) {
      fs.writeFile('text.txt', dataDemo1, 'utf8', function(err) {
        if (err)
          reject(err);
        else
          resolve("Promise Success!");
      });
    });
  }
doctorlee
  • 437
  • 4
  • 5
10

sync and async file reading way:

//fs module to read file in sync and async way

var fs = require('fs'),
    filePath = './sample_files/sample_css.css';

// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
});*/

//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);

Node Cheat Available at read_file.

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
7
var path = "index.html"

const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

using simple readFileSync works for me.

SuperNova
  • 25,512
  • 7
  • 93
  • 64
6
var fs = require('fs');
var path = (process.cwd()+"\\text.txt");

fs.readFile(path , function(err,data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});
krlzlx
  • 5,752
  • 14
  • 47
  • 55
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
6
var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

This is just because node is asynchronous and it will not wait for the read function and as soon as the program starts it will console the value as undefined, Which is actually true because there is no value assigned to content variable. To handle we can use promises, generators etc. We can use promise in this way.

new Promise((resolve,reject)=>{
    fs.readFile('./index.html','utf-8',(err, data)=>{
        if (err) {
            reject(err); // in the case of error, control flow goes to the catch block with the error occured.
        }
        else{
            resolve(data);  // in the case of success, control flow goes to the then block with the content of the file.
        }
    });
})
.then((data)=>{
    console.log(data); // use your content of the file here (in this then).    
})
.catch((err)=>{
    throw err; //  handle error here.
})
Nouman Dilshad
  • 1,014
  • 13
  • 16
5

The following is function would work for async wrap or promise then chains

const readFileAsync =  async (path) => fs.readFileSync(path, 'utf8');
rab
  • 4,134
  • 1
  • 29
  • 42
  • 1
    You're not making the function async by putting an await on it, it will still do a sync read and return a promise that resolves straight away – Dominic Sep 09 '20 at 11:08
  • readFileSync is sync function so use with await that isn't make scene . We should wrap `readFile` with `util.promisify(readFile)` then you can use `await` . Hope this help !! – Le Quang Nov 27 '20 at 08:31
3

you can read file by

var readMyFile = function(path, cb) {
      fs.readFile(path, 'utf8', function(err, content) {
        if (err) return cb(err, null);
        cb(null, content);
      });
    };

Adding on you can write to file,

var createMyFile = (path, data, cb) => {
  fs.writeFile(path, data, function(err) {
    if (err) return console.error(err);
    cb();
  });
};

and even chain it together

var readFileAndConvertToSentence = function(path, callback) {
  readMyFile(path, function(err, content) {
    if (err) {
      callback(err, null);
    } else {
      var sentence = content.split('\n').join(' ');
      callback(null, sentence);
    }
  });
};
J. Doe
  • 515
  • 4
  • 2
3

To put it roughly, you're dealing with node.js which is asynchronous in nature.

When we talk about async, we're talking about doing or processing info or data while dealing with something else. It is not synonymous to parallel, please be reminded.

Your code:

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

With your sample, it basically does the console.log part first, thus the variable 'content' being undefined.

If you really want the output, do something like this instead:

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

This is asynchronous. It will be hard to get used to but, it is what it is. Again, this is a rough but fast explanation of what async is.

DayIsGreen
  • 255
  • 1
  • 4
  • 16
0

I like using fs-extra because all functions are promisified, right out of the box, so you can use await. So your code could look like this:

(async () => {
   try {
      const content = await fs.readFile('./Index.html');
      console.log(content);
   } catch (err) {
      console.error(err);
   }
})();
Doug Barbieri
  • 635
  • 1
  • 5
  • 16