Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Renaming & Deleting Files
interview

Q1. How do you rename a file in Node.js?
Use fs.rename(oldPath, newPath, callback). Example:
fs.rename('oldname.txt', 'newname.txt', (err) => { if (err) throw err; console.log('Renamed'); });
This works for both files and directories. The operation is atomic - if it fails, the original file remains unchanged.

Q2. How do you delete a file?
Use fs.unlink() to delete a file. Example:
fs.unlink('file.txt', (err) => { if (err && err.code !== 'ENOENT') throw err; console.log('Deleted'); });
ENOENT error means file doesn't exist, which you might want to ignore. For synchronous deletion, use fs.unlinkSync().

Q3. How do you move a file?
Moving a file is essentially renaming with a different path:
fs.rename('file.txt', 'newfolder/file.txt', (err) => { ... });
This works within the same filesystem. For cross-device moves, you might need to copy the file then delete the original, or use streams.

Q4. How do you handle errors when deleting non-existent files?
Check the error code. Example:
fs.unlink('file.txt', (err) => { if (err && err.code === 'ENOENT') { console.log('File already gone'); } else if (err) { throw err; } });
You can also use fs.access() to check existence first, but that creates a race condition. Handling the specific error is more reliable.

Q5. How do you delete a non-empty directory?
For Node.js 14+, use fs.rm() with recursive option:
fs.rm('folder', { recursive: true, force: true }, (err) => { ... });
force: true ignores if folder doesn't exist. For older versions, you'd need to recursively delete contents first, or use third-party packages like rimraf.