|
1 | | -import { createWriteStream } from 'fs'; |
2 | | -import { readFile, unlink } from 'fs/promises'; |
3 | | -import path from 'path'; |
4 | 1 | import sanitize from 'sanitize-html'; |
5 | 2 | import { Readable } from 'stream'; |
6 | | - |
7 | | -import { TMP_FOLDER } from '../../utils/config'; |
8 | | -import { randomHexOf4 } from '../utils'; |
| 3 | +import { text } from 'stream/consumers'; |
9 | 4 |
|
10 | 5 | export function sanitizeHtml(content: string): string { |
11 | 6 | return sanitize(content); |
12 | 7 | } |
13 | 8 |
|
14 | | -export function createSanitizedFile( |
| 9 | +export async function sanitizeDocument( |
15 | 10 | file: Readable, |
16 | 11 | sanitizeFn: (content: string) => string, |
17 | 12 | ): Promise<Readable> { |
18 | | - return new Promise((done, rejects) => { |
19 | | - // create tmp file to read |
20 | | - const tmpFile = path.join(TMP_FOLDER, `${Date.now().toString()}_${randomHexOf4()}`); |
21 | | - file.pipe(createWriteStream(tmpFile)); |
22 | | - |
23 | | - file.on('error', function () { |
24 | | - rejects(new Error('An error happened while piping the file to sanitize')); |
25 | | - }); |
26 | | - |
27 | | - file.on('close', async function () { |
28 | | - const content = await readFile(tmpFile, { |
29 | | - encoding: 'utf8', |
30 | | - flag: 'r', |
31 | | - }); |
32 | | - |
33 | | - const readable = Readable.from(sanitizeFn(content)); |
34 | | - |
35 | | - // delete tmp file |
36 | | - unlink(tmpFile).catch((e) => console.error(e)); |
37 | | - |
38 | | - // return sanitized readable |
39 | | - done(readable); |
40 | | - }); |
41 | | - }); |
| 13 | + try { |
| 14 | + const content = await text(file); |
| 15 | + const readable = Readable.from(sanitizeFn(content)); |
| 16 | + |
| 17 | + // return sanitized readable |
| 18 | + return readable; |
| 19 | + } catch (e) { |
| 20 | + console.error(e); |
| 21 | + throw new Error('An error happened while creating a sanitized version of the file'); |
| 22 | + } |
42 | 23 | } |
0 commit comments