@@ -88,6 +88,14 @@ function getConfigPath(param) {
8888 if ( ! rootPath ) return value ;
8989 return path . resolve ( rootPath , value ) ;
9090}
91+
92+ // Write atomically via temp file + rename so readers don't observe a truncated/empty file
93+ function atomicWriteFile ( filePath , content ) {
94+ const tempPath = `${ filePath } .${ process . pid } .${ Date . now ( ) } .tmp` ;
95+ fs . writeFileSync ( tempPath , content ) ;
96+ fs . renameSync ( tempPath , filePath ) ;
97+ }
98+
9199/**
92100 * Builds the Harper config file using user inputs and default values from defaultConfig.yaml
93101 * @param args - any args that the user provided.
@@ -164,7 +172,7 @@ function createConfigFile(args, skipFsValidation = false) {
164172 true
165173 ) ;
166174 }
167- fs . writeFileSync ( configFilePath , String ( configDoc ) ) ;
175+ atomicWriteFile ( configFilePath , String ( configDoc ) ) ;
168176 logger . trace ( `Config file written to ${ configFilePath } ` ) ;
169177}
170178
@@ -389,7 +397,7 @@ function checkForUpdatedConfig(configDoc, configFilePath) {
389397 HTTP_STATUS_CODES . INTERNAL_SERVER_ERROR
390398 ) ;
391399 }
392- fs . writeFileSync ( configFilePath , String ( configDoc ) ) ;
400+ atomicWriteFile ( configFilePath , String ( configDoc ) ) ;
393401 }
394402}
395403
@@ -633,7 +641,7 @@ function updateConfigValue(
633641 HTTP_STATUS_CODES . INTERNAL_SERVER_ERROR
634642 ) ;
635643 }
636- fs . writeFileSync ( configFileLocation , String ( configDoc ) ) ;
644+ atomicWriteFile ( configFileLocation , String ( configDoc ) ) ;
637645 if ( update_config_obj ) {
638646 flatConfigObj = flattenConfig ( configDoc . toJSON ( ) ) ;
639647 }
@@ -895,7 +903,7 @@ function applyRuntimeEnvVarConfig(configDoc, configFilePath, options = {}) {
895903 HTTP_STATUS_CODES . INTERNAL_SERVER_ERROR
896904 ) ;
897905 }
898- fs . writeFileSync ( configFilePath , String ( configDoc ) ) ;
906+ atomicWriteFile ( configFilePath , String ( configDoc ) ) ;
899907 logger . debug ( 'Config file updated with runtime env var values' ) ;
900908 } catch ( error ) {
901909 logger . error ( `Failed to write config file after applying runtime env vars: ${ error . message } ` ) ;
@@ -956,7 +964,7 @@ async function addConfig(topLevelElement, values) {
956964 HTTP_STATUS_CODES . INTERNAL_SERVER_ERROR
957965 ) ;
958966 }
959- await fs . writeFile ( getConfigFilePath ( ) , String ( configDoc ) ) ;
967+ atomicWriteFile ( getConfigFilePath ( ) , String ( configDoc ) ) ;
960968}
961969
962970function deleteConfigFromFile ( param ) {
@@ -965,7 +973,7 @@ function deleteConfigFromFile(param) {
965973 configDoc . deleteIn ( param ) ;
966974 const hdbRoot = configDoc . getIn ( [ 'rootPath' ] ) ;
967975 const configFileLocation = path . join ( hdbRoot , hdbTerms . HARPER_CONFIG_FILE ) ;
968- fs . writeFileSync ( configFileLocation , String ( configDoc ) ) ;
976+ atomicWriteFile ( configFileLocation , String ( configDoc ) ) ;
969977}
970978
971979function getConfigObj ( ) {
0 commit comments