Skip to content

Instantly share code, notes, and snippets.

@isaacs isaacs/rename.js
Last active Dec 6, 2019

Embed
What would you like to do?
const fs = require('fs')
let path = 'foo'
try { fs.mkdirSync(path) } catch (e) {}
const stream = fs.createWriteStream(path + '/bar')
const write = (i = 10) => {
console.error('WRITE', i)
if (i === 0)
return stream.end()
stream.write('hello ' + i + '\n')
setTimeout(() => write(i - 1), 100)
}
stream.on('open', () => {
console.error('OPEN')
write()
setTimeout(() => {
console.error('TRY RENAME DURING WRITES')
try {
fs.renameSync(path, path + '-renamed-during-write')
path += '-renamed-during-write'
} catch (er) {
console.error('RENAME DURING WRITES FAILED', er)
}
console.log('RENAME DURING WRITES WORKED')
})
})
stream.on('close', () => {
console.error('TRY RENAME AFTER CLOSE')
try {
fs.renameSync(path, path + '-renamed-after-close')
path += '-renamed-after-close'
} catch (er) {
console.error('RENAME AFTER CLOSE FAILED', er)
}
console.log('RENAME AFTER CLOSE WORKED')
})
process.on('exit', () => console.log(path))
@isaacs

This comment has been minimized.

Copy link
Owner Author

isaacs commented Dec 6, 2019

This works on Unix, but the rename during writes fails on windows.

If I had a virus checker or some other process that locks directories for a moment when new files are created, then the "rename after close" will fail as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.