How can I lock a file while writing to it asynchronously
<p>I've got two node threads running, one watching a directory for file consumption and another that is responsible for writing files to given directories.</p>

<p>Typically they won't be operating on the same directory, but for an edge case I'm working on they will be. </p>

<p>It appears that the consuming app is grabbing the files before they are fully written, resulting in corrupt files.</p>

<p>Is there a way I can lock the file until the writing is complete? I've looked into the <code>lockfile</code> module, but unfortunately I don't believe it will work for this particular application.</p>

<p>=====</p>

<p>The full code is far more than makes sense to put here, but the gist of it is this:</p>

<ol>
<li>App spins off the watchers and listener</li>
</ol>

<p>Listener:</p>

<ul>
<li>listen for file being added to db, export it using <code>fs.writeFile</code></li>
</ul>

<p>Watcher:</p>

<ul>
<li>watcher uses <code>chokidar</code> to track added files in each watched directory</li>
<li>when found <code>fs.access</code> is called to ensure we have access to the file

<ul>
<li><code>fs.access</code> seems to be unfazed by file being written</li>
</ul></li>
<li>the file is consumed via <code>fs.createReadStream</code> and then sent to server

<ul>
<li>filestream is necessary as we need the file hash</li>
</ul></li>
</ul>

<p>In this case the file is exported to the watched directory and then reimported 
by the watch process.</p>