Convert fs-utils module to typescript

Change-type: patch
Signed-off-by: Cameron Diver <cameron@resin.io>
This commit is contained in:
Cameron Diver 2018-06-14 22:23:41 +01:00
parent c9904d8b5d
commit d656fbb1f5
No known key found for this signature in database
GPG Key ID: 69264F9C923F55C1
3 changed files with 24 additions and 27 deletions

View File

@ -1,24 +0,0 @@
Promise = require 'bluebird'
fs = Promise.promisifyAll(require('fs'))
path = require 'path'
exports.writeAndSyncFile = (path, data) ->
fs.openAsync(path, 'w')
.then (fd) ->
fs.writeAsync(fd, data, 0, 'utf8')
.then ->
fs.fsyncAsync(fd)
.then ->
fs.closeAsync(fd)
exports.writeFileAtomic = (path, data) ->
exports.writeAndSyncFile("#{path}.new", data)
.then ->
fs.renameAsync("#{path}.new", path)
exports.safeRename = (src, dest) ->
fs.renameAsync(src, dest)
.then ->
fs.openAsync(path.dirname(dest), 'r')
.tap(fs.fsyncAsync)
.then(fs.closeAsync)

View File

@ -1,3 +0,0 @@
export function writeAndSyncFile(path: string, data: string): Promise<void>;
export function writeFileAtomic(path: string, data: string): Promise<void>;
export function safeRename(src: string, dest: string): Promise<void>;

24
src/lib/fs-utils.ts Normal file
View File

@ -0,0 +1,24 @@
import * as Bluebird from 'bluebird';
import { fs } from 'mz';
import * as path from 'path';
export function writeAndSyncFile(path: string, data: string): Bluebird<void> {
return Bluebird.resolve(fs.open(path, 'w'))
.then((fd) => {
fs.write(fd, data, 0, 'utf8')
.then(() => fs.fsync(fd))
.then(() => fs.close(fd));
});
}
export function writeFileAtomic(path: string, data: string): Bluebird<void> {
return Bluebird.resolve(writeAndSyncFile(`${path}.new`, data))
.then(() => fs.rename(`${path}.new`, path));
}
export function safeRename(src: string, dest: string): Bluebird<void> {
return Bluebird.resolve(fs.rename(src, dest))
.then(() => fs.open(path.dirname(dest), 'r'))
.tap(fs.fsync)
.then(fs.close);
}