Node.js


Filesystem I/O All Versions

v0.1
v0.2
v0.3
v0.4
v0.5
v0.6
v0.7
v0.8
v0.9
v0.10
v0.11
io.js v1.0
io.js v1.1
io.js v1.2
io.js v1.3
io.js v1.4
io.js v1.5
io.js v1.6
io.js v1.7
io.js v1.8
io.js v2.0
io.js v2.1
io.js v2.2
io.js v2.3
io.js v2.4
io.js v2.5
io.js v3.0
io.js v3.1
io.js v3.2
io.js v3.3
v4.0
v4.1
v4.2
v5.0
v5.1
v5.2
v5.3
v5.4
v5.5
v0.12
v4.3
v5.6
v5.7
v4.4
v5.8
v5.9
v5.10
v5.10.1
v5.11.0
v6.0.0
v5.11.1
v6.1.0
v6.2.0
v6.2.1
v6.2.2
v5.12.0
v6.3.0
v6.3.1

Improvements requested by Chandan Kharbanda:

  • This topic would benefit from examples that don't currently exist. - Aug 22 at 20:38
    Comments:
    • yield examples for ECMAScript 6 users would be certainly helpful - Chandan Kharbanda

This draft deletes the entire topic.

expand all collapse all

Examples

  • 5

    Use the filesystem module for all file operations:

    const fs = require('fs');
    

    With Encoding

    In this example, read hello.txt from the directory /tmp. This operation will be completed in the background and the callback occurs on completion or failure:

    fs.readFile('/tmp/hello.txt', { encoding: 'utf8' }, (err, content) => {
      // If an error occurred, output it and return
      if(err) return console.error(err);
    
      // No error occurred, content is a string
      console.log(content);
    });
    

    Without Encoding

    Read the binary file binary.txt from the current directory, asynchronously in the background. Note that we do not set the 'encoding' option - this prevents Node.js from decoding the contents into a string:

    fs.readFile('binary.txt', (err, binaryContent) => {
      // If an error occurred, output it and return
      if(err) return console.error(err);
    
      // No error occurred, content is a Buffer, output it in
      // hexadecimal representation.
      console.log(content.toString('hex'));
    });
    
  • 2
    const fs = require('fs');
    
    // Read the contents of the directory /usr/local/bin asynchronously.
    // The callback will be invoked once the operation has either completed
    // or failed.
    fs.readdir('/usr/local/bin', function(err, files) {
      // On error, show it and return
      if(err) return console.error(err);
    
      // files is an array containing the names of all entries
      // in the directory, excluding '.' (the directory itself)
      // and '..' (the parent directory).
    
      // Display directory entries
      console.log( files.join(' ') );
    });
    

    A synchronous variant is available as readdirSync which blocks the main thread and therefore prevents execution of asynchronous code at the same time. Most developers avoid synchronous IO functions in order to improve performance.

    let files;
    try {
      files = fs.readdirSync('/var/tmp');
    } catch(err) {
      // An error occurred
      console.error(err);
    }
    

    Using a generator

    const fs = require('fs');
    
    // Iterate through all items obtained via
    // 'yield' statements
    // A callback is passed to the generator function because it is required by
    // the 'readdir' method
    function run(gen) {
      var iter = gen(function (err, data) {
        if (err) { iter.throw(err); }
        return iter.next(data);
      });
      iter.next();
    }
    
    const dirPath = '/usr/local/bin';
    
    // Execute the generator function
    run(function* (resume) {
      // Emit the list of files in the directory from the generator
      var contents = yield fs.readdir(dirPath, resume);
      console.log(contents);
    });
    
  • 1

    fs.access() determines whether a path exists and what permissions a user has to the file or directory at that path. fs.access doesn't return a result rather, if it doesn't return an error, the path exists and the user has the desired permissions.

    The permission modes are available as a property on the fs object, fs.constants

    • fs.constants.F_OK - Has read/write/execute permissions (If no mode is provided, this is the default)
    • fs.constants.R_OK - Has read permissions
    • fs.constants.W_OK - Has write permissions
    • fs.constants.X_OK - Has execute permissions (Works the same as fs.constants.F_OK on Windows)

    Asynchronously

    var fs = require('fs');
    var path = '/path/to/check';
    
    // checks execute permission
    fs.access(path, fs.constants.X_OK, (err) => {
        if (err) {
            console.log("%s doesn't exist", path);
        } else {
            console.log('can execute %s', path);
        }
    });
    // Check if we have read/write permissions
    // When specifying multiple permission modes
    // each mode is separated by a pipe : `|`
    fs.access(path, fs.constants.R_OK | fs.constants.W_OK, (err) => {
        if (err) {
            console.log("%s doesn't exist", path);
        } else {
            console.log('can read/write %s', path);
        }
    });
    

    Synchronously

    fs.access also has a synchronous version fs.accessSync. When using fs.accessSync you must enclose it within a try/catch block.

    // Check write permission
    try {
        fs.accessSync(path, fs.constants.W_OK);
        console.log('can write %s', path);
    }
    catch (err) {
        console.log("%s doesn't exist", path);
    }
    

I am downvoting this example because it is...

Syntax

Syntax

Parameters

Parameters

Remarks

In Node.js, resource intensive operations such as I/O are performed asynchronously, but have a synchronous counterpart (e.g. there exists a fs.readFile and its counterpart is fs.readFileSync). Since Node is single-threaded, you should be careful when using synchronous operations, because they will block the entire process.

If a process is blocked by a synchronous operation, the entire execution cycle (including the event loop) is halted. That means other asynchronous code, including events and event handlers, will not run and your program will continue to wait until the single blocking operation has completed.

There are appropriate uses for both synchronous and asynchronous operations, but care must be taken that they are utilized properly.

Still have a question about Filesystem I/O? Ask Question

Topic Outline