import { fromPromise } from 'neverthrow'
import { promises as fs } from 'fs'
type FileError =
| { type: 'NotFound'; path: string }
| { type: 'PermissionDenied'; path: string }
| { type: 'Unknown'; message: string }
function readFile(path: string) {
return fromPromise(
fs.readFile(path, 'utf-8'),
(error): FileError => {
if (error instanceof Error) {
if (error.message.includes('ENOENT')) {
return { type: 'NotFound', path }
}
if (error.message.includes('EACCES')) {
return { type: 'PermissionDenied', path }
}
return { type: 'Unknown', message: error.message }
}
return { type: 'Unknown', message: 'Unknown error' }
}
)
}
const result = await readFile('config.json')
result.match(
(content) => console.log('File content:', content),
(error) => {
switch (error.type) {
case 'NotFound':
console.log('File not found:', error.path)
break
case 'PermissionDenied':
console.log('Permission denied:', error.path)
break
case 'Unknown':
console.log('Error:', error.message)
break
}
}
)