2019-11-02 14:03:41 +00:00
|
|
|
import { readdir, readFile as readBack, writeFile as writeBack } from 'fs';
|
2019-06-16 21:35:43 +00:00
|
|
|
import { isNil } from 'lodash';
|
|
|
|
import { promisify } from 'util';
|
2019-06-15 22:38:05 +00:00
|
|
|
|
2019-06-16 21:35:43 +00:00
|
|
|
export const FILE_ENCODING = 'utf-8';
|
2019-11-02 14:03:41 +00:00
|
|
|
|
|
|
|
export const readDir = promisify(readdir);
|
2019-11-02 12:35:20 +00:00
|
|
|
export const readFile = promisify(readBack);
|
|
|
|
export const writeFile = promisify(writeBack);
|
2019-06-15 22:38:05 +00:00
|
|
|
|
2019-11-14 01:32:20 +00:00
|
|
|
export async function readSource(path: string, stream = process.stdin): Promise<string> {
|
2019-06-15 22:38:05 +00:00
|
|
|
if (path === '-') {
|
2019-11-14 01:32:20 +00:00
|
|
|
return readStream(stream, FILE_ENCODING);
|
2019-06-15 22:38:05 +00:00
|
|
|
} else {
|
2019-11-02 12:35:20 +00:00
|
|
|
return readFile(path, {
|
2019-06-16 21:35:43 +00:00
|
|
|
encoding: FILE_ENCODING,
|
|
|
|
});
|
2019-06-15 22:38:05 +00:00
|
|
|
}
|
|
|
|
}
|
2019-06-16 01:21:11 +00:00
|
|
|
|
2019-11-14 01:32:20 +00:00
|
|
|
export function readStream(stream: NodeJS.ReadStream, encoding: string): Promise<string> {
|
|
|
|
return new Promise((res, rej) => {
|
|
|
|
const chunks: Array<Buffer> = [];
|
|
|
|
stream.on('data', (chunk) => chunks.push(chunk));
|
|
|
|
stream.on('end', () => {
|
|
|
|
const result = Buffer.concat(chunks).toString(encoding);
|
|
|
|
res(result);
|
2019-06-16 21:35:43 +00:00
|
|
|
});
|
2019-11-14 01:32:20 +00:00
|
|
|
stream.on('error', (err) => rej(err));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function writeSource(path: string, data: string, stream = process.stdout): Promise<void> {
|
|
|
|
if (path === '-') {
|
|
|
|
return writeStream(stream, data);
|
2019-06-16 01:21:11 +00:00
|
|
|
} else {
|
2019-11-02 12:35:20 +00:00
|
|
|
return writeFile(path, data, {
|
2019-06-16 21:35:43 +00:00
|
|
|
encoding: FILE_ENCODING,
|
2019-06-16 01:21:11 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2019-11-14 01:32:20 +00:00
|
|
|
|
|
|
|
export function writeStream(stream: NodeJS.WriteStream, data: string): Promise<void> {
|
|
|
|
return new Promise((res, rej) => {
|
|
|
|
stream.write(data, (err: Error | null | undefined) => {
|
|
|
|
if (isNil(err)) {
|
|
|
|
res();
|
|
|
|
} else {
|
|
|
|
rej(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|