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.
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' ]
The following is a list of all wrapped functions...
fs.access(path: string, mode?: number|string): Promise<void>
fs.appendFile(file: string|number, data: any, options?: { encoding?: string; mode?: number|string; flag?: string; }): Promise<void>
fs.chmod(path: string, mode: number|string): Promise<void>
fs.chown(path: string, uid: number, gid: number): Promise<void>
fs.close(fd: number): Promise<void>
fs.fchmod(fd: number, mode: number|string): Promise<void>
fs.fchown(fd: number, uid: number, gid: number): Promise<void>
fs.fstat(fd: number): Promise<Stats>
fs.fsync(fd: number): Promise<void>
fs.ftruncate(fd: number, len?: number): Promise<void>
fs.futimes(fd: number, atime: Date|number, mtime: Date|number): Promise<void>
fs.lchmod(path: string, mode: number|string): Promise<void>
fs.lchown(path: string, uid: number, gid: number): Promise<void>
fs.link(srcpath: string, dstpath: string): Promise<void>
fs.lstat(path: string): Promise<Stats>
fs.mkdir(path: string, mode?: number|string): Promise<void>
fs.mkdtemp(prefix: string): Promise<string>
fs.open(path: string, flags: string, mode?: number|string): Promise<number>
fs.read(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<ReadResult>
fs.readdir(path: string): Promise<string[]>
fs.readFile(file: string|number, options?: {encoding?: string, flag?: string}|string): Promise<any>
fs.readlink(path: string): Promise<string>
fs.realpath(path: string, cache?: {[path: string]: string}): Promise<string>
fs.rename(oldPath: string, newPath: string): Promise<void>
fs.rmdir(path: string): Promise<void>
fs.stat(path: string): Promise<Stats>
fs.symlink(srcpath: string, dstpath: string, type?: string): Promise<void>
fs.truncate(path: string, len?: number): Promise<void>
fs.unlink(path: string): Promise<void>
fs.utimes(path: string, atime: Date|number, mtime: Date|number): Promise<void>
fs.write(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number): Promise<{written: number; buffer: Buffer}>
fs.write(fd: number, data: any, offset?: number, position?: number, encoding?: string): Promise<{written: number; buffer: Buffer}>
fs.write(fd: number): Promise<{written: number; buffer: Buffer}>
fs.writeFile(file: string|number, data: string|any, options?: {encoding?: string, flag?: string, mode?: number|string}): Promise<void>
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.
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');
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.
Here are some other TypeScript async/await wrappers you may find useful...
- async-parallel simplifies invoking tasks in parallel
- web-request simplifies making web requests