async-file

Adapts the Node.js File System API (fs) for use with TypeScript async/await


Keywords
async, await, typescript, promise, promisify, file, fs
License
MIT
Install
npm install async-file@2.0.2

Documentation

async-file

Adapts the Node.js File System API (fs) for use with TypeScript async/await

This package makes it easier to access the Node.js file system using TypeScript and async/await. It wraps the Node.js File System API, replacing callback functions with functions that return a Promise.

Basically it lets you write your code like this...

await fs.unlink('/tmp/hello');
console.log('successfully deleted /tmp/hello');

instead of like this...

fs.unlink('/tmp/hello', err => {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

Or like this...

await fs.rename('/tmp/hello', '/tmp/world');
var stats = await fs.stat('/tmp/hello', '/tmp/world');
console.log(`stats: ${JSON.stringify(stats)}`);

instead of this...

fs.rename('/tmp/hello', '/tmp/world', (err) => {
  if (err) throw err;
  fs.stat('/tmp/world', (err, stats) => {
    if (err) throw err;
    console.log(`stats: ${JSON.stringify(stats)}`);
  });
});

This package is a drop-in replacement for fs typings in node.d.ts—simply import async-file instead of fs and call any method within an async function...

import * as fs from 'async-file';
(async function () {
    var data = await fs.readFile('data.csv', 'utf8');
    await fs.rename('/tmp/hello', '/tmp/world');
    await fs.access('/etc/passd', fs.constants.R_OK | fs.constants.W_OK);
    await fs.appendFile('message.txt', 'data to append');
    await fs.unlink('/tmp/hello');
})();

In addition several convenience functions are introduced to simplify accessing text-files, testing for file existance, and creating or deleting files and directories recursively. Other than the modified async function signatures and added convenience functions, the interface of this wrapper is virtually identical to the native Node.js file system library.

Getting Started

Make sure you're running Node v4 and TypeScript 1.8 or higher...

$ node -v
v4.2.6
$ npm install -g typescript
$ npm install -g tsd
$ tsc -v
Version 1.8.9

Install async-file package and required node.d.ts dependencies...

$ npm install async-file
$ tsd install node

Write some code...

import * as fs from 'async-file';
(async function () {
    var list = await fs.readdir('.');
    console.log(list);    
})();

Save the above to a file (index.ts), build and run it!

$ tsc index.ts typings/node/node.d.ts --target es6 --module commonjs 
$ node index.js
[ 'index.js', 'index.ts', 'node_modules', 'typings' ]

Wrapped Functions

The following is a list of all wrapped functions...

Convenience Functions

In addition to the wrapped functions above, the following convenience functions are provided...

  • fs.createDirectory(path, mode?: number|string): Promise<void>
  • fs.delete(path: string): Promise<void>
  • fs.exists(path: string): Promise<boolean>
  • fs.readTextFile(file: string|number, encoding?: string, flags?: string): Promise<string>
  • fs.writeTextFile(file: string|number, data: string, encoding?: string, mode?: string): Promise<void>
  • fs.mkdirp(path: string): Promise<void>
  • fs.rimraf(path: string): Promise<void>

fs.createDirectory creates a directory recursively (like mkdirp).

fs.delete deletes any file or directory, performing a deep delete on non-empty directories (wraps rimraf).

fs.exists implements the recommended solution of opening the file and returning true when the ENOENT error results.

fs.readTextFile and fs.writeTextFile are optimized for simple text-file access, dealing exclusively with strings not buffers or streaming.

fs.mkdirp and fs.rimraf are aliases for fs.createDirectory and fs.delete respectively, for those prefering more esoteric nomenclature.

Convenience Function Examples

Read a series of three text files, one at a time...

var data1 = await fs.readTextFile('data1.csv');
var data2 = await fs.readTextFile('data2.csv');
var data3 = await fs.readTextFile('data3.csv');

Append a line into an arbitrary series of text files...

var files = ['data1.log', 'data2.log', 'data3.log'];
for (var file of files)
    await fs.writeTextFile(file, '\nPASSED!\n', null, 'a');

Check for the existance of a file...

if (!(await fs.exists('config.json')))
    console.warn('Configuration file not found');

Create a directory...

await fs.createDirectory('/tmp/path/to/file');

Delete a file or or directory...

await fs.delete('/tmp/path/to/file');

Additional Notes

If access to both the native Node.js file system library and the wrapper is required at the same time (e.g. to mix callbacks alongside async/await code), specify a different name in the import statement of the wrapper...

import * as fs from 'fs';
import * as afs from 'async-file';
await afs.rename('/tmp/hello', '/tmp/world');
fs.unlink('/tmp/hello', err => 
  console.log('/tmp/hello deleted', err));
});

By design none of "sync" functions are exposed by the wrapper: fs.readFileSync, fs.writeFileSync, etc.

Related Wrappers

Here are some other TypeScript async/await wrappers you may find useful...