One way to check if a file exists on the file system in TypeScript is to use the fs.existsSync()
method provided by the Node.js fs
module.
Here is an example code snippet that demonstrates how to check if a file exists:
index.ts178 chars10 lines
In the code above, we first import the fs
module using a wildcard import (* as fs
) to get access to all the methods provided by the module. We then declare a filePath
variable that holds the path to the file we want to check.
Next, we use the fs.existsSync()
method to check if the file exists. If the file does exist, we log a message to the console indicating that the file exists. Otherwise, we log a message indicating that the file does not exist.
Note that fs.existsSync()
is a synchronous method, which means that it blocks the thread until it completes. If you want to perform the check asynchronously, you can use the fs.access()
method instead.
gistlibby LogSnag