1
1
module . exports . register = function ( Handlebars , options ) {
2
2
Handlebars . registerHelper ( 'versionedAsset' , function ( options ) {
3
- // requiring crypto library for hashing
3
+ // node libraries
4
4
const crypto = require ( 'crypto' ) ;
5
- // retrieving full path to the asset from the handlebar helper context
6
- const path = options . fn ( this ) ;
7
- const hash = crypto . createHash ( 'sha256' ) ;
5
+ const path = require ( 'path' ) ;
8
6
const fs = require ( 'fs' ) ;
9
- const ext = __dirname . substr ( 0 , __dirname . length - 9 ) . replace ( "/src" , "/dist" ) ;
7
+ const filePath = options . fn ( this ) ;
8
+ const hash = crypto . createHash ( 'sha256' ) ;
9
+ // creating full path from the root dir to the file
10
+ const fullPath = path . join ( __dirname , "../../.." , "dist" , filePath ) ;
10
11
let hashCode = "" ;
11
12
hash . on ( 'readable' , ( ) => {
12
13
const data = hash . read ( ) ;
13
14
if ( data ) hashCode = data . toString ( 'hex' ) ;
14
15
} )
15
- hash . write ( fs . readFileSync ( ext + path , function ( err ) { if ( err ) return 0 } ) . toString ( ) ) ;
16
+ hash . write ( fs . readFileSync ( fullPath , function ( err ) { if ( err ) return 0 } ) . toString ( ) ) ;
16
17
hash . end ( ) ;
17
- hashCode = "/" + path + "?v=" + hashCode . substr ( 0 , 6 ) ;
18
+ // creating a version string from first 6 hash characters
19
+ hashCode = filePath + "?v=" + hashCode . substr ( 0 , 6 ) ;
18
20
return hashCode ;
19
21
} ) ;
20
22
} ;
0 commit comments