fs#constants TypeScript Examples
The following examples show how to use
fs#constants.
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: utils.ts From rewind with MIT License | 7 votes |
/**
* Checks certain files to see if Rewind can be booted without any problems with the given `osuFolderPath`.
* @param osuFolderPath the folder path to check the files in
*/
export async function osuFolderSanityCheck(osuFolderPath: string) {
try {
await Promise.all(filesToCheck.map((f) => access(join(osuFolderPath, f), constants.R_OK)));
} catch (err) {
Logger.log(err);
return false;
}
return true;
}
Example #2
Source File: utils.ts From rewind with MIT License | 7 votes |
// Just keeping it here just in case
async function createFolderIfNotExisting(folderPath: string) {
try {
await access(folderPath, constants.R_OK);
} catch (err) {
Logger.log(`Could not access the replays folder '${folderPath}'. Creating a new one`);
// TODO: Access rights?
return mkdir(folderPath);
}
}
Example #3
Source File: MigrationService.ts From context-mod with MIT License | 6 votes |
async backupDatabase() {
try {
if (this.database.options.type === 'sqljs' && this.database.options.location !== undefined) {
try {
const ts = Date.now();
const backupLocation = `${this.database.options.location}.${ts}.bak`
this.dbLogger.info(`Detected sqljs (sqlite) database. Will try to make a backup at ${backupLocation}`, {leaf: 'Backup'});
await copyFile(this.database.options.location, backupLocation, constants.COPYFILE_EXCL);
this.dbLogger.info('Successfully created backup!', {leaf: 'Backup'});
} catch (err: any) {
throw new ErrorWithCause('Cannot make an automated backup of your configured database.', {cause: err});
}
} else {
let msg = 'Cannot make an automated backup of your configured database.';
if (this.database.options.type !== 'sqljs') {
msg += ' Only SQlite (sqljs database type) is implemented for automated backups right now, sorry :( You will need to manually backup your database.';
} else {
// TODO don't throw for this??
msg += ' Database location is not defined (probably in-memory).';
}
throw new Error(msg);
}
} catch (e: any) {
this.dbLogger.error(e, {leaf: 'Backup'});
throw e;
}
}
Example #4
Source File: FilesystemChecker.ts From Bridge with GNU General Public License v3.0 | 6 votes |
/**
* Verifies that the user has specified a library folder.
*/
private checkLibraryFolder() {
if (getSettings().libraryPath == undefined) {
this.callbacks.error(filesystemErrors.libraryFolder(), () => this.beginCheck())
} else {
access(getSettings().libraryPath, constants.W_OK, this.cancelable((err) => {
if (err) {
this.callbacks.error(filesystemErrors.libraryAccess(err), () => this.beginCheck())
} else {
this.checkDestinationFolder()
}
}))
}
}
Example #5
Source File: FilesystemChecker.ts From Bridge with GNU General Public License v3.0 | 6 votes |
/**
* Checks that the destination folder doesn't already exist.
*/
private checkDestinationFolder() {
const destinationPath = join(getSettings().libraryPath, this.destinationFolderName)
access(destinationPath, constants.F_OK, this.cancelable((err) => {
if (err) { // File does not exist
this.createDownloadFolder()
} else {
this.callbacks.error(filesystemErrors.destinationFolderExists(destinationPath), () => this.beginCheck())
}
}))
}
Example #6
Source File: fetch-platform-data.ts From F95API with MIT License | 6 votes |
//#endregion Public methods
//#region Private methods
/**
* Read the platform cache (if available).
*/
async function readCache(path: string): Promise<boolean> {
// Local variables
let returnValue = false;
async function checkFileExists(file: string) {
return fs
.access(file, constants.F_OK)
.then(() => true)
.catch(() => false);
}
const existsCache = await checkFileExists(path);
if (existsCache) {
const data = await fs.readFile(path, { encoding: "utf-8", flag: "r" });
const json: Record<string, Record<string, string>> = JSON.parse(data);
// Map objects don't natively support JSON conversion
// so they were saved as normal object and we need to
// re-covert them
shared.setPrefixPair("engines", objectToMap(json.engines));
shared.setPrefixPair("statuses", objectToMap(json.statuses));
shared.setPrefixPair("tags", objectToMap(json.tags));
shared.setPrefixPair("others", objectToMap(json.others));
returnValue = true;
}
return returnValue;
}
Example #7
Source File: resolver.ts From devoirs with MIT License | 6 votes |
{ S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IXGRP, S_IROTH, S_IXOTH, } = constants
Example #8
Source File: cache.ts From optimized-images-loader with MIT License | 6 votes |
isValidCacheFolder = async (cacheFolder: string): Promise<boolean> => {
// try accessing the parent folder
try {
await fs.access(path.dirname(cacheFolder));
} catch {
return false;
}
// check if the folder already exists
try {
await fs.access(cacheFolder, constants.W_OK);
return true;
} catch {
// otherwise try to create the cache folder
try {
await fs.mkdir(cacheFolder);
return true;
} catch (e) {
return e.code === 'EEXIST';
}
}
}
Example #9
Source File: index.ts From node-duckdb with MIT License | 6 votes |
export async function writeSyntheticParquetFile(
path: string,
numberOfRows: number,
forceRewrite: boolean,
): Promise<void> {
let doesFileExist = true;
try {
await access(path, constants.F_OK);
} catch (e) {
doesFileExist = false;
}
if (!forceRewrite && doesFileExist) {
console.log(`${path} exists`);
return;
}
if (forceRewrite && doesFileExist) {
await unlink(path);
}
console.log("writing synthetic file");
const writer = await parquet.ParquetWriter.openFile(new parquet.ParquetSchema(schema), path);
for (let i = 0; i < numberOfRows; i++) {
const row = Object.assign(
{},
...columnTypes.map((columnType, index) => ({ [`col${index}`]: getRandomValue(columnType) })),
);
await writer.appendRow(row);
}
await writer.close();
console.log("finished writing synthetic file");
}
Example #10
Source File: file-session.impl.ts From dev-manager-desktop with Apache License 2.0 | 6 votes |
function getFileType(attrs: Attributes): FileType {
if (S_ISTYPE(attrs, constants.S_IFREG)) {
return '-';
} else if (S_ISTYPE(attrs, constants.S_IFDIR)) {
return 'd';
} else if (S_ISTYPE(attrs, constants.S_IFLNK)) {
return 'l';
} else if (S_ISTYPE(attrs, constants.S_IFIFO)) {
return 'p';
} else if (S_ISTYPE(attrs, constants.S_IFSOCK)) {
return 's';
} else if (S_ISTYPE(attrs, constants.S_IFBLK)) {
return 'b';
} else if (S_ISTYPE(attrs, constants.S_IFCHR)) {
return 'c';
} else {
return '';
}
}
Example #11
Source File: fetchPackages.ts From lucide with ISC License | 5 votes |
fileExist = (filePath) => fs.access(filePath, constants.F_OK).then(() => true).catch(() => false)
Example #12
Source File: lsp.ts From coffeesense with MIT License | 5 votes |
private warnProjectIfNeed(projectConfig: ProjectConfig) {
if (projectConfig.lspFullConfig.coffeesense.ignoreProjectWarning) {
return;
}
const isFileCanAccess = (fsPath: string) => {
try {
accessSync(fsPath, constants.R_OK);
return true;
} catch {
return false;
}
};
const showErrorIfCantAccess = (name: string, fsPath: string) => {
this.lspConnection.window.showErrorMessage(`CoffeeSense can't access ${fsPath} for ${name}.`);
};
const showWarningAndLearnMore = (message: string, url: string) => {
this.lspConnection.window.showWarningMessage(message, { title: 'Learn More' }).then(action => {
if (action) {
this.openWebsite(url);
}
});
};
const getCantFindMessage = (fileNames: string[]) =>
`CoffeeSense can't find ${fileNames.map(el => `\`${el}\``).join(' or ')} in ${projectConfig.rootFsPath}.`;
if (!projectConfig.tsconfigPath) {
showWarningAndLearnMore(
getCantFindMessage(['tsconfig.json', 'jsconfig.json']),
'https://github.com/phil294/coffeesense/blob/master/docs/guide/FAQ.md#coffeesense-can-t-find-tsconfig-json-jsconfig-json-in-xxxx-xxxxxx'
);
} else if (!isFileCanAccess(projectConfig.tsconfigPath)) {
showErrorIfCantAccess('ts/js config', projectConfig.tsconfigPath);
} else {
if (
!projectConfig.isExistCoffeeSenseConfig &&
![
normalizeFileNameResolve(projectConfig.rootFsPath, 'tsconfig.json'),
normalizeFileNameResolve(projectConfig.rootFsPath, 'jsconfig.json')
].includes(projectConfig.tsconfigPath ?? '')
) {
showWarningAndLearnMore(
`CoffeeSense found \`tsconfig.json\`/\`jsconfig.json\`, but they aren\'t in the project root.`,
'https://github.com/phil294/coffeesense/blob/master/docs/guide/FAQ.md#coffeesense-found-xxx-but-they-aren-t-in-the-project-root'
);
}
}
if (!projectConfig.packagePath) {
showWarningAndLearnMore(
getCantFindMessage(['package.json']),
'https://github.com/phil294/coffeesense/blob/master/docs/guide/FAQ.md#coffeesense-can-t-find-package-json-in-xxxx-xxxxxx'
);
} else if (!isFileCanAccess(projectConfig.packagePath)) {
showErrorIfCantAccess('ts/js config', projectConfig.packagePath);
} else {
if (
!projectConfig.isExistCoffeeSenseConfig &&
normalizeFileNameResolve(projectConfig.rootFsPath, 'package.json') !== projectConfig.packagePath
) {
showWarningAndLearnMore(
`CoffeeSense found \`package.json\`/, but it isn\'t in the project root.`,
'https://github.com/phil294/coffeesense/blob/master/docs/guide/FAQ.md#coffeesense-found-xxx-but-they-aren-t-in-the-project-root'
);
}
}
}
Example #13
Source File: file-session.impl.ts From dev-manager-desktop with Apache License 2.0 | 5 votes |
function S_ISTYPE(attrs: Attributes, type: number): boolean {
return (attrs.mode & constants.S_IFMT) == type;
}
Example #14
Source File: vite.ts From farrow with MIT License | 4 votes |
vite = (options?: FarrowViteOptions): ViteRouterPipeline => {
const router = Router()
const config = {
...options,
}
let viteDevServers: ViteDevServer[] = []
router.useLazy(async () => {
const viteServer = await createViteServer({
server: {
...config.server,
middlewareMode: true,
},
...config,
})
const getHtmlPath = async (url: string): Promise<string> => {
const pathname = url.split('?')[0]
/**
* pathname.slice(1) is to remove the first '/'
* /dir/file.html => dir/file.html
* path.join('/root', 'dir/file.html') => /root/dir/file.html
*/
const filename = path.join(viteServer.config.root, pathname.slice(1))
if (filename.endsWith('.html')) {
return filename
}
const maybeHtmlPath = `${filename}/index.html`
try {
await fs.access(maybeHtmlPath, constants.R_OK)
return `${filename}/index.html`
} catch (error) {
// if subfolder has no index.html found, use the root folder's instead
return `${viteServer.config.root}/index.html`
}
}
const handler: CustomBodyHandler = ({ req, res }) => {
viteServer.middlewares(req, res, async () => {
try {
const url = req.url ?? '/'
const htmlPath = await getHtmlPath(url)
const fileContent = await fs.readFile(htmlPath, 'utf-8')
const html = await viteServer.transformIndexHtml(url, fileContent)
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
if (options?.onBeforeSendHtml) {
res.end(await options.onBeforeSendHtml(html))
} else {
res.end(html)
}
} catch (error: any) {
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/plain')
}
const message = process.env.NODE_ENV === 'production' ? error.message : error.stack ?? error.message
res.statusCode = 500
res.end(message ?? '')
}
})
}
viteDevServers.push(viteServer)
return () => {
return Response.custom(handler)
}
})
return {
...router,
async close() {
const servers = [...viteDevServers]
viteDevServers = []
await Promise.all(servers.map((server) => server.close()))
},
}
}