(
filePath: string,
data: Buffer | string,
options: BufferEncoding | { encoding?: BufferEncoding; flag?: string } = {},
)
| 111 | } |
| 112 | |
| 113 | async writeFile( |
| 114 | filePath: string, |
| 115 | data: Buffer | string, |
| 116 | options: BufferEncoding | { encoding?: BufferEncoding; flag?: string } = {}, |
| 117 | ) { |
| 118 | filePath = path.normalize(filePath); |
| 119 | |
| 120 | if (typeof options === 'string') { |
| 121 | options = { |
| 122 | encoding: options, |
| 123 | }; |
| 124 | } |
| 125 | |
| 126 | const flag = options && options.flag ? options.flag : 'w'; |
| 127 | const encoding = options && options.encoding ? options.encoding : 'utf8'; |
| 128 | |
| 129 | // Make sure file doesn't exist for "x" flags |
| 130 | if (flag[1] === 'x') { |
| 131 | await this._assertDoesNotExist(filePath); |
| 132 | } |
| 133 | |
| 134 | const dirEntry: FSDir = this._assertDir(path.dirname(filePath)); |
| 135 | |
| 136 | let file: FSEntry | null = this._find(filePath); |
| 137 | |
| 138 | if (file) { |
| 139 | file = this._assertFileEntry(file); |
| 140 | } else { |
| 141 | const name = path.basename(filePath); |
| 142 | file = { |
| 143 | name, |
| 144 | type: 'file', |
| 145 | ino: this.__ino++, |
| 146 | mtimeMs: Date.now(), |
| 147 | contents: '', |
| 148 | path: filePath, |
| 149 | }; |
| 150 | dirEntry.children.push(file); |
| 151 | } |
| 152 | |
| 153 | const dataBuff: Buffer = data instanceof Buffer ? data : Buffer.from(data, encoding); |
| 154 | let newContents = Buffer.alloc(0); |
| 155 | |
| 156 | if (flag[0] === 'w') { |
| 157 | newContents = dataBuff; |
| 158 | } else if (flag[0] === 'a') { |
| 159 | const contentsBuff: Buffer = Buffer.from(file.contents, 'base64'); |
| 160 | newContents = Buffer.concat([contentsBuff, dataBuff]); |
| 161 | } else { |
| 162 | throw new SystemError({ |
| 163 | code: 'EBADF', |
| 164 | errno: -9, |
| 165 | message: 'EBADF: bad file descriptor, write', |
| 166 | path: filePath, |
| 167 | syscall: 'write', |
| 168 | }); |
| 169 | } |
| 170 |
no test coverage detected