I found a better solution with the help of a package (https://github.com/ronomon/opened) -
const checkFileIsOpen = async (fileName: string): Promise<boolean> => {
try {
// myAppDocsPath is a variable of my application specific path
const filePath = myAppDocsPath + '/' + fileName
const paths = [filePath]
return new Promise((resolve, reject) => {
Opened.files(paths, function (error: any, hashTable: Record<string, boolean>) {
console.log(hashTable)
if (error) throw reject(false)
resolve(hashTable[paths[0]])
})
})
} catch (error) {
console.log('Check file is open error:\n', error)
return false
}
}
For a list of file -
type FileListOpenStatus = Record<string, boolean> | false
const checkFileListOpenStatus = async (fileNameList: string[]): Promise<FileListOpenStatus> => {
try {
// myAppDocsPath is a variable of my application specific path
const paths = fileNameList.map((fileName) => `${myAppDocsPath}/${fileName}`)
return new Promise((resolve, reject) => {
Opened.files(paths, function (error: any, hashTable: Record<string, boolean>) {
console.log(hashTable)
if (error) throw reject(false)
const results: Record<string, boolean> = {}
for (const [filePath, value] of Object.entries(hashTable)) {
const fileName = path.basename(filePath)
results[fileName] = value
}
resolve(results)
})
})
} catch (error) {
console.log('Check file list open status error:\n', error)
return false
}
}