fs/promises#open TypeScript Examples
The following examples show how to use
fs/promises#open.
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: addBot.ts From context-mod with MIT License | 5 votes |
addBot = () => {
const middleware = [
authUserCheck(),
];
const response = async (req: Request, res: Response) => {
if (!req.user?.isInstanceOperator(req.app)) {
return res.status(401).send("Must be an Operator to use this route");
}
if (!req.botApp.fileConfig.isWriteable) {
return res.status(409).send('Operator config is not writeable');
}
const {overwrite = false, ...botData} = req.body;
// check if bot is new or overwriting
let existingBot = req.botApp.bots.find(x => x.botAccount === botData.name);
// spin down existing
if (existingBot !== undefined) {
const {
bots: botsFromConfig = []
} = req.botApp.fileConfig.document.toJS();
if(botsFromConfig.length === 0 || botsFromConfig.some(x => x.name !== botData.name)) {
req.botApp.logger.warn('Overwriting existing bot with the same name BUT this bot does not exist in the operator CONFIG FILE. You should check how you have provided config before next start or else this bot may be started twice (once from file, once from arg/env)');
}
await existingBot.destroy('system');
req.botApp.bots.filter(x => x.botAccount !== botData.name);
}
req.botApp.fileConfig.document.addBot(botData);
const handle = await open(req.botApp.fileConfig.document.location as string, 'w');
await handle.writeFile(req.botApp.fileConfig.document.toString());
await handle.close();
const newBot = new Bot(buildBotConfig(botData, req.botApp.config), req.botApp.logger);
req.botApp.bots.push(newBot);
let result: any = {stored: true, success: true};
try {
if (newBot.error !== undefined) {
result.error = newBot.error;
return res.status(500).json(result);
}
await newBot.testClient();
await newBot.buildManagers();
newBot.runManagers('system').catch((err) => {
req.botApp.logger.error(`Unexpected error occurred while running Bot ${newBot.botName}. Bot must be re-built to restart`);
if (!err.logged || !(err instanceof LoggedError)) {
req.botApp.logger.error(err);
}
});
} catch (err: any) {
result.success = false;
if (newBot.error === undefined) {
newBot.error = err.message;
result.error = err.message;
}
req.botApp.logger.error(`Bot ${newBot.botName} cannot recover from this error and must be re-built`);
if (!err.logged || !(err instanceof LoggedError)) {
req.botApp.logger.error(err);
}
}
return res.json(result);
}
return [...middleware, response];
}
Example #2
Source File: ipc.ts From cloudmusic-vscode with MIT License | 4 votes |
export async function initIPC(context: ExtensionContext): Promise<void> {
const ipcHandler = (data: IPCServerMsg | NeteaseAPISMsg<NeteaseAPIKey>) => {
switch (data.t) {
case IPCApi.netease:
{
const req = IPC.requestPool.get(data.channel);
if (!req) break;
IPC.requestPool.delete(data.channel);
if ((data.msg as { err?: true })["err"] === true) req.reject();
else req.resolve(data.msg);
}
break;
case IPCControl.netease:
AccountManager.accounts.clear();
data.profiles.forEach((i) => AccountManager.accounts.set(i.userId, i));
PlaylistProvider.refresh();
RadioProvider.refresh();
AccountViewProvider.account(data.profiles);
State.downInit(); // 2
if (State.master) {
if (!data.cookies.length) IPC.clear();
void context.secrets.store(COOKIE_KEY, JSON.stringify(data.cookies));
}
break;
case IPCControl.master:
State.master = !!data.is;
break;
case IPCControl.new:
IPC.new();
break;
case IPCControl.retain:
QueueProvider.new(data.items as PlayTreeItemData[]);
State.downInit(); // 1
break;
case IPCPlayer.end:
if (!data.fail && State.repeat) IPC.load();
else void commands.executeCommand("cloudmusic.next");
break;
case IPCPlayer.loaded:
State.loading = false;
break;
case IPCPlayer.lyric:
State.lyric = {
...State.lyric,
...data.lyric,
};
break;
case IPCPlayer.lyricIndex:
ButtonManager.buttonLyric(State.lyric.text[data.idx][State.lyric.type]);
State.lyric.updateIndex?.(data.idx);
break;
case IPCPlayer.pause:
ButtonManager.buttonPlay(false);
AccountViewProvider.pause();
break;
case IPCPlayer.play:
ButtonManager.buttonPlay(true);
AccountViewProvider.play();
break;
case IPCPlayer.stop:
ButtonManager.buttonSong();
ButtonManager.buttonLyric();
State.lyric = {
...State.lyric,
...defaultLyric,
};
AccountViewProvider.stop();
break;
case IPCPlayer.volume:
ButtonManager.buttonVolume(data.level);
break;
case IPCPlayer.next:
void commands.executeCommand("cloudmusic.next");
break;
case IPCPlayer.previous:
void commands.executeCommand("cloudmusic.previous");
break;
case IPCPlayer.speed:
ButtonManager.buttonSpeed(data.speed);
break;
case IPCQueue.fm:
State.fm = true;
break;
case IPCQueue.fmNext:
State.playItem = QueueItemTreeItem.new({
...data.item,
pid: data.item.al.id,
});
break;
case IPCWasm.load:
AccountViewProvider.wasmLoad(data.path);
break;
case IPCWasm.pause:
AccountViewProvider.wasmPause();
break;
case IPCWasm.play:
AccountViewProvider.wasmPlay();
break;
case IPCWasm.stop:
AccountViewProvider.wasmStop();
break;
case IPCWasm.volume:
AccountViewProvider.wasmVolume(data.level);
break;
case IPCWasm.speed:
AccountViewProvider.wasmSpeed(data.speed);
break;
}
};
try {
const firstTry = await IPC.connect(ipcHandler, ipcBHandler, 0);
if (firstTry.includes(false)) throw Error;
} catch {
State.first = true;
State.downInit(); // 1
const version = (context.extension.packageJSON as { version: string })
.version;
const log = `err-${version}.log`;
const logPath = resolve(SETTING_DIR, log);
const httpProxy =
workspace.getConfiguration("http").get<string>("proxy") ||
process.env.HTTPS_PROXY ||
process.env.HTTP_PROXY;
const ipcServerPath = resolve(context.extensionPath, "dist", "server.js");
const conf = CONF();
spawn(process.execPath, [...process.execArgv, ipcServerPath], {
detached: true,
shell: false,
stdio: ["ignore", "ignore", (await open(logPath, "a")).fd],
env: {
...process.env,
// eslint-disable-next-line @typescript-eslint/naming-convention
...(STRICT_SSL ? {} : { NODE_TLS_REJECT_UNAUTHORIZED: "0" }),
// eslint-disable-next-line @typescript-eslint/naming-convention
...(httpProxy ? { GLOBAL_AGENT_HTTP_PROXY: httpProxy } : {}),
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_SETTING_DIR: SETTING_DIR,
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_NATIVE_MODULE: NATIVE_MODULE,
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_VOLUME: context.globalState.get(VOLUME_KEY, 85).toString(),
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_SPEED: context.globalState.get(SPEED_KEY, 1).toString(),
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_WASM: State.wasm ? "1" : "0",
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_MUSIC_QUALITY: MUSIC_QUALITY(conf).toString(),
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_MUSIC_CACHE_SIZE: MUSIC_CACHE_SIZE(conf).toString(),
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_HTTPS_API: HTTPS_API(conf) ? "1" : "0",
// eslint-disable-next-line @typescript-eslint/naming-convention
CM_FOREIGN: FOREIGN(conf) ? "1" : "0",
},
}).unref();
await IPC.connect(ipcHandler, ipcBHandler);
readdir(SETTING_DIR, { withFileTypes: true })
.then((dirents) => {
for (const dirent of dirents) {
if (
dirent.isFile() &&
dirent.name.startsWith("err") &&
dirent.name !== log
)
rm(resolve(SETTING_DIR, dirent.name), {
recursive: true,
force: true,
}).catch(console.error);
}
})
.catch(console.error);
}
}