Skip to content

Commit

Permalink
append using stream
Browse files Browse the repository at this point in the history
  • Loading branch information
milesstoetzner committed Sep 24, 2023
1 parent 913c102 commit a1246ee
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
26 changes: 24 additions & 2 deletions src/target/file.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import Target from '#/target/target'
import * as check from '#check'
import Message from '#core/message'
import * as files from '#files'
import std from '#std'
import fs from 'node:fs'

export type FileTargetOptions = {
file: string
}

export class FileTarget extends Target {
options: FileTargetOptions
stream?: fs.WriteStream

constructor(options: FileTargetOptions) {
super()
Expand All @@ -17,19 +19,39 @@ export class FileTarget extends Target {

async start() {
std.log('starting file target')

this.stream = fs.createWriteStream(this.options.file, {flags: 'a'})
this.setReady()

std.log('file target started')
}

async stop() {
std.log('stopping file target')

await new Promise<void>((resolve, reject) => {
if (check.isUndefined(this.stream)) {
std.log('file not opened')
return resolve()
}
this.stream.end(() => resolve())
})

std.log('file target stopped')
}

async send(message: Message) {
std.log('file target sending', {message})
message.clean()
await files.appendFile(this.options.file, message.toString() + '\n')

await new Promise<void>((resolve, reject) => {
if (check.isUndefined(this.stream)) return std.log('file not opened')
this.stream.write(message.toString() + '\n', error => {
if (check.isDefined(error)) std.log(error)
return resolve()
})
})

std.log('file target sent')
}
}
9 changes: 0 additions & 9 deletions src/utils/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,6 @@ export async function createFile(file: string) {
await handle.close()
}

export async function appendFile(file: string, data: string) {
return new Promise((resolve, reject) => {
fs.appendFile(path.resolve(file), data, error => {
if (check.isDefined(error)) return reject(error)
return resolve(file)
})
})
}

export function storeFile(file: string, data: string) {
fs.writeFileSync(path.resolve(file), data)
return file
Expand Down

0 comments on commit a1246ee

Please sign in to comment.