Source

fs-file.write.class.ts

  1. import { writeFile, createWriteStream, appendFile, WriteFileOptions, WriteStream, ReadStream } from 'fs';
  2. /**
  3. * Contains methods that write to file
  4. */
  5. export interface PromiseLikeWriteStream extends WriteStream, PromiseLike<void> {}
  6. export class FSFileWrite {
  7. constructor(public readonly path: string) {}
  8. /**
  9. * Writes string to file
  10. * @param txt - content to write
  11. */
  12. async txt(txt: string) {
  13. return new Promise<void>((resolve, reject) => {
  14. writeFile(this.path, txt, err => {
  15. if (err) return reject(err);
  16. resolve();
  17. });
  18. });
  19. }
  20. /**
  21. * Serialize onject to JSON and writes it to file
  22. * @param obj - object to serialize
  23. */
  24. async json(obj: object) {
  25. await this.txt(JSON.stringify(obj));
  26. }
  27. /**
  28. * Creates fs WriteStream for this path.
  29. * @param options - node fs.createWriteStream options
  30. * @returns thenable stream, which resolves on stream close
  31. */
  32. createWriteStream(options?: SecondArgument<typeof createWriteStream>) {
  33. const stream = createWriteStream(this.path, options) as PromiseLikeWriteStream;
  34. const promise = new Promise<void>((resolve, reject) => {
  35. stream.once('close', () => {
  36. resolve();
  37. });
  38. stream.once('error', err => reject(err));
  39. });
  40. stream.then = promise.then.bind(promise);
  41. return stream;
  42. }
  43. /**
  44. * Asynchronously append data to a file, creating the file if it does not yet exist.
  45. * @param data - string or Buffer to append
  46. * @param options
  47. */
  48. async appendFile(data: string | Buffer, options?: WriteFileOptions) {
  49. return new Promise<void>((resolve, reject) => {
  50. const cb = (err: Error | null) => {
  51. if (err) return reject(err);
  52. resolve();
  53. };
  54. if (options) {
  55. appendFile(this.path, data, options, cb);
  56. } else {
  57. appendFile(this.path, data, cb);
  58. }
  59. });
  60. }
  61. /**
  62. * Writes stream to file.
  63. * @param stream - input stream
  64. */
  65. async writeFromStream(stream: ReadStream) {
  66. const target = this.createWriteStream();
  67. stream.pipe(target);
  68. await target;
  69. }
  70. }
  71. type SecondArgument<T> = T extends (arg1: any, arg2: infer U, ...args: any[]) => any ? U : any;