1+ import { createHash } from 'node:crypto'
12import fs , { promises as fsp } from 'node:fs'
23import path from 'node:path'
34import { pathToFileURL } from 'node:url'
5+ import { attempt , attemptAsync } from '@pengzhanbo/utils'
46
57interface LoadFromCodeOptions {
68 filepath : string
@@ -17,17 +19,18 @@ export async function loadFromCode<T = any>({
1719} : LoadFromCodeOptions ) : Promise < T | { [ key : string ] : T } > {
1820 filepath = path . resolve ( cwd , filepath )
1921 const ext = isESM ? '.mjs' : '.cjs'
20- const filepathTmp = `${ filepath } .timestamp-${ Date . now ( ) } ${ ext } `
21- const file = pathToFileURL ( filepathTmp ) . toString ( )
22+ const filepathTmp = `${ filepath } .${ getHash ( code ) } ${ ext } `
2223 await fsp . writeFile ( filepathTmp , code , 'utf8' )
23- try {
24- const mod = await import ( file )
25- return mod . default || mod
26- }
27- finally {
28- try {
29- fs . unlinkSync ( filepathTmp )
30- }
31- catch { }
32- }
24+ const [ , mod ] = await attemptAsync ( importDefault , String ( pathToFileURL ( filepathTmp ) ) )
25+ attempt ( fs . unlinkSync , filepathTmp )
26+ return mod
27+ }
28+
29+ async function importDefault ( filepath : string ) : Promise < any > {
30+ const mod = await import ( filepath )
31+ return mod . default || mod
32+ }
33+
34+ function getHash ( str : string ) : string {
35+ return createHash ( 'md5' ) . update ( str ) . digest ( 'hex' )
3336}
0 commit comments