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