see if a file exists on file system in typescript

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.ts
import * as fs from 'fs';

const filePath = '/path/to/file.txt';

if (fs.existsSync(filePath)) {
  console.log('File exists!');
} else {
  console.log('File does not exist.');
}
178 chars
10 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