I thought it would be a cool experiment to have a for loop and create a file hello.txt and then delete it with unlink. I figured that if fs.unlink is the delete file procedure in Node, then fs.link must be the create file. However, my code will only delete, and it will not create, not even once. Even if I separate the fs.link code into a separate file, it still will not create my file hello.txt.
Below is my code:
var fs = require('fs'),
for(var i=1;i<=10;i++){
fs.unlink('./hello.txt', function (err) {
if (err){
throw err;
} else {
console.log('successfully deleted file');
}
fs.link('./hello.txt', function (err) {
if (err){
throw err;
} else {
console.log('successfully created file');
}
});
});
}
http://nodejs.org/api/fs.html#fs_fs_link_srcpath_dstpath_callback
Thank you!
fs.open() using the ‘w’ param will work to create a file. As you proceed, you may encounter a second issue with your code, along the lines of this:
With some additional logging, you’ll see that the code you’re using doesn’t actually trigger creation actions for “hello1.txt” through “hello10.txt” followed by deletion actions for the same. (Or in your sample, deletions, followed by creations, though I changed this while debugging because create/delete made more sense to me.)
More to the point, the asynchronous callbacks seem to all use the final “i” value, rather than the value of “i” during the relevant loop.
Long story short, I made the concept work by making a separate function which performed the desired create/delete for a given filename, and then call this function from the for loop. This seems to be a more reliable way to ensure that the intended value of “i” is used throughout the action sequence, rather than changing between the initial step and the callback step.