11#!/usr/bin/env node
22const fs = require ( 'fs' ) ;
3+ const { promises : fsp } = fs ;
34const path = require ( 'path' ) ;
45const glob = require ( 'glob' ) ;
56const util = require ( 'util' ) ;
@@ -25,6 +26,8 @@ async function reskindex() {
2526 const header = args . h || args . header ;
2627
2728 const strm = fs . createWriteStream ( componentIndexTmp ) ;
29+ // Wait for the open event to ensure the file descriptor is set
30+ await new Promise ( resolve => strm . once ( "open" , resolve ) ) ;
2831
2932 if ( header ) {
3033 strm . write ( fs . readFileSync ( header ) ) ;
@@ -53,14 +56,9 @@ async function reskindex() {
5356
5457 strm . write ( "export {components};\n" ) ;
5558 // Ensure the file has been fully written to disk before proceeding
59+ await util . promisify ( fs . fsync ) ( strm . fd ) ;
5660 await util . promisify ( strm . end ) ;
57- fs . rename ( componentIndexTmp , componentIndex , function ( err ) {
58- if ( err ) {
59- console . error ( "Error moving new index into place: " + err ) ;
60- } else {
61- console . log ( 'Reskindex: completed' ) ;
62- }
63- } ) ;
61+ await fsp . rename ( componentIndexTmp , componentIndex ) ;
6462}
6563
6664// Expects both arrays of file names to be sorted
@@ -77,15 +75,23 @@ function filesHaveChanged(files, prevFiles) {
7775 return false ;
7876}
7977
78+ // Wrapper since await at the top level is not well supported yet
79+ function run ( ) {
80+ ( async function ( ) {
81+ await reskindex ( ) ;
82+ console . log ( "Reskindex completed" ) ;
83+ } ) ( ) ;
84+ }
85+
8086// -w indicates watch mode where any FS events will trigger reskindex
8187if ( ! args . w ) {
82- reskindex ( ) ;
88+ run ( ) ;
8389 return ;
8490}
8591
8692let watchDebouncer = null ;
8793chokidar . watch ( path . join ( componentsDir , componentJsGlob ) ) . on ( 'all' , ( event , path ) => {
8894 if ( path === componentIndex ) return ;
8995 if ( watchDebouncer ) clearTimeout ( watchDebouncer ) ;
90- watchDebouncer = setTimeout ( reskindex , 1000 ) ;
96+ watchDebouncer = setTimeout ( run , 1000 ) ;
9197} ) ;
0 commit comments