In this section I will be going over some basic node delete file examples, using the fs.unlink method in the file system module. There is an older callback style way of using it and then there is doing what is squire to ensure a promise is returned.
Here we have a basic example of the fs.unlink method example that will delete a file that is given as an argument when used in the command line with node. In this example I am using the old callback style of these kinds of method where I just call the method, pass the path to the file I want to delete, and then pass a callback that will fire when the task is over.
If there is an error there will be an error object, if not the value of the argument will be null. This style of example will work on a wide range of node versions, but most developers myself included prefer promises these days, o lets look at another basic example of the node delete fs.unlink method.
Then there is making sure that the use of the fs.unlink method will return a promise when used.
So now for a more advanced example that is starting to look like some kind of project. This will still be a very simple example just for the sake of this post, that involves creating a json file that will just store a count. This json file is created if it is not there, is opened stepped, and saved if it is there, and of course there is a command to delete the file.
So this example might serve as a good starting point when it comes to getting use to how to go about using not just the node delete fs.unlink method, but also methods like fs.readFile, fs.writeFile, and the use of promises as a way to keep things well structured.
I have a step count method that will read a json file that stores a current count. In the event that it is there to begin with it will step the current value by one and then write the updated state to the file. In the event that it is not there it will write a new json file at start it off with some default values. In any case it will resolve with the current state, unless some error other than just a ENOENT error happens when reading the json file.
Then of course there is the delete count method that uses the fs.unlink method to delete the json file. The I have a run method that will process the current command when it comes to using the script from the command line with node. I can just call the script and it will create or update the json file, and I can also give a kill command option that will delete the file.
Maybe it is not the most compelling example of the node delete unlink method, but often this kind of thing does come up in real projects. Say I have some kind of productivity tool that stores config settings in work folder. I would want some code that would read it if it is all ready there, and create it with default settings if it is not.
In some situations, such as I might want some code that deletes the file for whatever the reason as well.