Part of my application involves deleting a large folder and some rows that relate to the files in that folder in a database periodically.
To do this I was thinking of using this code:
const { rmdir } = require('fs/promises');
... begin transaction
... remove database rows
await rmdir(dir, { recursive: true });
... end transaction
The reason I want to use the Promises API instead of rmdirSync (which stops the entire server) is that I want the server to keep accepting requests while the operating system is busy deleting the folder. I know I could just use the callback api and just end the transaction before the folder is deleted, but that may lead to inconsistencies and also wouldn't catch any potential errors. (the files might still be served by express.static
while the database rows are already gone)
But I read in this documentation: https://nodejs.org/api/fs.html#fs_callback_example That the use of the Promise API is not recommended in favour of the callback API.
So here's my questions:
Why is it slower to use the Promise API instead of the Callback API?
How much slower?
Could I just do this instead:
const { unlink } = require('fs');
... begin transaction
... remove database rows
await new Promise((res,rej)=>{
unlink('/tmp/hello', (err) => {
resolve()
})
});
... end transaction
The promises api does exactly the same thing as your included code:
await new Promise((resolve, reject)=>{
unlink('/tmp/hello', (err) => {
if (err) {
return reject(err)
}
resolve()
})
});
The memory and time difference is directly related to the promises. Callback API uses bare c++, but promises require an additional layer of logic.
There is probably no difference until you make a million operations per second.