2
2
3
3
// Require some libs used for creating temporary files
4
4
import os from "os"
5
- import fs from "fs"
5
+ import * as fs from "fs"
6
6
import path from "path"
7
- import { v1 as uuidv1 } from "uuid"
7
+ import * as temp from "temp"
8
+ temp . track ( )
8
9
9
10
// Public: GrammarUtils - utilities for determining how to run code
10
11
const GrammarUtils = {
@@ -17,17 +18,10 @@ const GrammarUtils = {
17
18
// Returns the {String} filepath of the new file
18
19
createTempFileWithCode ( code , extension = "" ) {
19
20
try {
20
- if ( ! fs . existsSync ( this . tempFilesDir ) ) {
21
- fs . mkdirSync ( this . tempFilesDir )
22
- }
23
-
24
- const tempFilePath = this . tempFilesDir + path . sep + uuidv1 ( ) + extension
25
-
26
- const file = fs . openSync ( tempFilePath , "w" )
27
- fs . writeSync ( file , code )
28
- fs . closeSync ( file )
29
-
30
- return tempFilePath
21
+ const tempFile = temp . openSync ( { dir : this . tempFilesDir , suffix : extension } )
22
+ fs . writeSync ( tempFile . fd , code )
23
+ fs . closeSync ( tempFile . fd )
24
+ return tempFile . path
31
25
} catch ( error ) {
32
26
throw new Error ( `Error while creating temporary file (${ error } )` )
33
27
}
@@ -37,14 +31,7 @@ const GrammarUtils = {
37
31
// {GrammarUtils::createTempFileWithCode}
38
32
deleteTempFiles ( ) {
39
33
try {
40
- if ( fs . existsSync ( this . tempFilesDir ) ) {
41
- const files = fs . readdirSync ( this . tempFilesDir )
42
- if ( files . length ) {
43
- files . forEach ( ( file ) => fs . unlinkSync ( this . tempFilesDir + path . sep + file ) )
44
- }
45
- return fs . rmdirSync ( this . tempFilesDir )
46
- }
47
- return null
34
+ return temp . cleanupSync ( )
48
35
} catch ( error ) {
49
36
throw new Error ( `Error while deleting temporary files (${ error } )` )
50
37
}
0 commit comments