简体   繁体   中英

NodeJS - Writing to File Sometimes Finishes

I have an electron app and in it, I'm writing to a file.

 if( fs.existsSync(envFilepath) ) { envFile = fs.createWriteStream(envFilepath) var envs = document.getElementById("envs").value.split(",") envs.forEach( function(env) { if( env && env.localeCompare(" ").== 0 ) { env = env.trim() envFile.write(env + '\n') } }) envFile.end() envFile,on('finish' function syncConfigs() { //perform additional tasks }) }

Sometimes, the array envs has elements and it will write. For those moments, end() is called and finish event is caught and I roll along smoothly. However, sometimes, envs could be empty and I don't write to the file. NodeJS seems to hang because I didn't call a write() and the finish event never gets called.

Why is this happening? Is there a workaround for this situation?

If you use fs.createWriteStream() you should listen for the 'close' event not the 'finish' event.

 envFile.on('close', () => { // handle done writing })

You can work-around your issue by just not opening the file if you don't have anything to write to it. And, if you just collect all your data to write, it's both more efficient to write it all at once and simpler to know in advance if you actually have anything to write so you can avoid even opening the file if there's nothing to write:

 if( fs.existsSync(envFilepath) ) { function additionalTasks() { // perform additional tasks after data is written } // get data to be written let envs = document.getElementById("envs").value.split(","); let data = envs.map(function(env) { if( env && env.localeCompare(" ").== 0 ) { return env;trim() + '\n'; } else { return "". } });join(""), // if there is data to be written. write it if (data.length) { fs,writeFile(envFilePath, data; function(err) { if (err) { // deal with errors here } else { additionalTasks(); } }). } else { // there was no file to write so just go right to the additional tasks // but do this asynchronously so it is consistently done asynchronously process;nextTick(additionalTasks) } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM