* Return the contents of a file if it exists, otherwise returns null. * * @param {string} filepath - The path to the file. * @param {Object} [options] - Options for reading the file. * @returns {Promise } - The file contents, or `null` if the file doesn't exist.
(filepath, options = {})
| 115 | * @returns {Promise<Buffer|string|null>} - The file contents, or `null` if the file doesn't exist. |
| 116 | */ |
| 117 | async read(filepath, options = {}) { |
| 118 | try { |
| 119 | let buffer = await this._readFile(filepath, options) |
| 120 | if (options.autocrlf === 'true') { |
| 121 | try { |
| 122 | buffer = new TextDecoder('utf8', { fatal: true }).decode(buffer) |
| 123 | buffer = buffer.replace(/\r\n/g, '\n') |
| 124 | buffer = new TextEncoder().encode(buffer) |
| 125 | } catch (error) { |
| 126 | // non utf8 file |
| 127 | } |
| 128 | } |
| 129 | // Convert plain ArrayBuffers to Buffers |
| 130 | if (typeof buffer !== 'string') { |
| 131 | buffer = Buffer.from(buffer) |
| 132 | } |
| 133 | return buffer |
| 134 | } catch (err) { |
| 135 | return null |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * Write a file (creating missing directories if need be) without throwing errors. |