fs-extra#close TypeScript Examples
The following examples show how to use
fs-extra#close.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DifferentialDownloader.ts From electron-differential-updater with MIT License | 6 votes |
private downloadFile(tasks: Array<Operation>, emit: Function): Promise<any> {
const fdList: Array<OpenedFile> = [];
const closeFiles = (): Promise<Array<void>> => {
return Promise.all(
fdList.map(openedFile => {
return close(openedFile.descriptor).catch(e => {
this.logger.error(`cannot close file "${openedFile.path}": ${e}`);
});
})
);
};
return this.doDownloadFile(tasks, fdList, emit)
.then(closeFiles)
.catch(e => {
// then must be after catch here (since then always throws error)
return closeFiles()
.catch(closeFilesError => {
// closeFiles never throw error, but just to be sure
try {
this.logger.error(`cannot close files: ${closeFilesError}`);
} catch (errorOnLog) {
try {
console.error(errorOnLog);
} catch (ignored) {
// ok, give up and ignore error
}
}
throw e;
})
.then(() => {
throw e;
});
});
}
Example #2
Source File: FileWithEmbeddedBlockMapDifferentialDownloader.ts From electron-differential-updater with MIT License | 6 votes |
async function readEmbeddedBlockMapData(file: string): Promise<BlockMap> {
const fd = await open(file, "r");
try {
const fileSize = (await fstat(fd)).size;
const sizeBuffer = Buffer.allocUnsafe(4);
await read(
fd,
sizeBuffer,
0,
sizeBuffer.length,
fileSize - sizeBuffer.length
);
const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0));
await read(
fd,
dataBuffer,
0,
dataBuffer.length,
fileSize - sizeBuffer.length - dataBuffer.length
);
await close(fd);
return readBlockMap(dataBuffer);
} catch (e) {
await close(fd);
throw e;
}
}
Example #3
Source File: createEmptyFile.test.ts From joplin-utils with MIT License | 6 votes |
describe('测试 createEmptyFile', () => {
const tempPath = path.resolve(__dirname, '.temp')
beforeEach(async () => {
await remove(tempPath)
await mkdirp(tempPath)
})
it.skip('基本示例', async () => {
const filePath = path.resolve(tempPath, 'test.drawio.svg')
let handle: number
try {
handle = await createEmptyFile(filePath)
expect(await readFile(filePath, 'utf-8')).toBe('')
} finally {
await close(handle!)
}
})
})
Example #4
Source File: DifferentialDownloader.ts From electron-differential-updater with MIT License | 4 votes |
private async doDownloadFile(
tasks: Array<Operation>,
fdList: Array<OpenedFile>,
emit: Function
): Promise<any> {
let oldFileFd: number;
oldFileFd = await open(this.options.oldFile, "r");
fdList.push({ descriptor: oldFileFd, path: this.options.oldFile });
const newFileFd = await open(this.options.newFile, "w");
fdList.push({ descriptor: newFileFd, path: this.options.newFile });
const fileOut = createWriteStream(this.options.newFile, {
fd: newFileFd
});
await new Promise((resolve, reject) => {
const streams: Array<any> = [];
const digestTransform = new DigestTransform(
this.blockAwareFileInfo.sha512
);
// to simply debug, do manual validation to allow file to be fully written
digestTransform.isValidateOnEnd = false;
streams.push(digestTransform);
// noinspection JSArrowFunctionCanBeReplacedWithShorthand
fileOut.on("finish", () => {
(fileOut.close as any)(() => {
// remove from fd list because closed successfully
fdList.splice(1, 1);
try {
digestTransform.validate();
} catch (e) {
reject(e);
return;
}
resolve();
});
});
streams.push(fileOut);
let lastStream = null;
for (const stream of streams) {
stream.on("error", reject);
if (lastStream == null) {
lastStream = stream;
} else {
lastStream = lastStream.pipe(stream);
}
}
const firstStream = streams[0];
// TASK - use useMultipleRangeRequest property from package.json
let w: any;
if (this.options.isUseMultipleRangeRequest) {
w = executeTasksUsingMultipleRangeRequests(
this,
tasks,
firstStream,
oldFileFd,
reject
);
w(0);
return;
}
let downloadOperationCount = 0;
let actualUrl: string | null = null;
this.logger.info(`Differential download: ${this.options.newUrl}`);
const requestOptions = this.createRequestOptions();
(requestOptions as any).redirect = "manual";
w = (index: number): void => {
if (index >= tasks.length) {
if (this.fileMetadataBuffer != null) {
firstStream.write(this.fileMetadataBuffer);
}
firstStream.end();
return;
}
const operation = tasks[index++];
if (operation.kind === OperationKind.COPY) {
copyData(operation, firstStream, oldFileFd, reject, () => w(index));
return;
}
const range = `bytes=${operation.start}-${operation.end - 1}`;
requestOptions.headers!!.range = range;
const debug = this.logger.debug;
if (debug != null) {
debug(`download range: ${range}`);
try {
emit(DOWNLOAD_PROGRESS, {
transferred: index,
total: tasks.length,
percent: (index / tasks.length) * 100
});
} catch (e) {
console.log(e);
}
}
const request = this.httpExecutor.createRequest(
requestOptions,
response => {
// Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
if (response.statusCode >= 400) {
reject(createHttpError(response));
}
response.pipe(firstStream, {
end: false
});
response.once("end", () => {
if (++downloadOperationCount === 100) {
downloadOperationCount = 0;
setTimeout(() => w(index), 1000);
} else {
w(index);
}
});
}
);
request.on(
"redirect",
(statusCode: number, method: string, redirectUrl: string) => {
this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`);
actualUrl = redirectUrl;
configureRequestUrl(new URL(actualUrl), requestOptions);
request.followRedirect();
}
);
this.httpExecutor.addErrorAndTimeoutHandlers(request, reject);
request.end();
};
w(0);
});
}