Using callback
const fs = require('fs'); const path = './file.txt'; fs.access(path, (error, stats) => { if (error) { console.error(error); } else { console.log(stats); } });
Using util.promisify
Node v8.0.0 added support for a built-in util.promisify.
const fs = require('fs'); const { promisify } = require('util'); const path = './file.txt'; // Convert `fs.access()` into a function that returns a promise const accessAsync = promisify(fs.access); (async () => { try { const stats = await accessAsync(path); console.log(stats); } catch (error) { console.error(error); } })();
Using fs.promises
The fs.promises API provides an alternative set of asynchronous file system methods that return Promise objects rather than using callbacks.
Node v10.0.0 added support for a built-in util.promisify.
const fsPromises = require('fs').promises; // Alternatively, you can import fs with require('fs/promises') const path = './file.txt'; (async () => { try { const stats = await fsPromises.stat(path); console.log(stats); } catch (error) { console.error(error); } })();