fs#unlink TypeScript Examples
The following examples show how to use
fs#unlink.
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: AttachmentsFilesService.ts From node-experience with MIT License | 6 votes |
static unlinkTempFilesAttachments(tempFilesAttachments: IFilesAttachments[]): void
{
if (tempFilesAttachments)
{
tempFilesAttachments.map(({ path }) =>
{
unlink(path, (err) =>
{
if (err)
{
throw err;
}
});
});
}
}
Example #2
Source File: FileExtractor.ts From Bridge with GNU General Public License v3.0 | 6 votes |
/**
* Tries to delete the archive at `fullPath`.
*/
private deleteArchive(fullPath: string) {
unlink(fullPath, this.cancelable((err) => {
if (err && err.code != 'ENOENT') {
devLog(`Warning: failed to delete archive at [${fullPath}]`)
}
this.callbacks.complete()
}))
}
Example #3
Source File: writeGitIgnore.ts From engine with MIT License | 5 votes |
pUnlink = promisify(unlink)
Example #4
Source File: duckdb-config.test.ts From node-duckdb with MIT License | 5 votes |
unlinkAsync = promisify(unlink)
Example #5
Source File: RestyaboardUtils.ts From vscode-restyaboard-viewer with MIT License | 5 votes |
export function removeTempRestyaboardFile() {
const userDataFolder = new UserDataFolder();
const tempRestyaboardFile = userDataFolder.getPathCodeSettings() + TEMP_RESTYABOARD_FILE_NAME;
unlink(tempRestyaboardFile, err => {
if (err) throw err;
console.info(`❌ Deleted file: ${tempRestyaboardFile}`);
});
}
Example #6
Source File: spLinter.ts From sourcepawn-vscode with MIT License | 4 votes |
/**
* Lint a TextDocument object and add its diagnostics to the
* @param {TextDocument} document The document to lint.
* @returns void
*/
export function refreshDiagnostics(document: TextDocument): void {
// Check if the user specified not to enable the linter for this file.
const range = new Range(0, 0, 1, 0);
const text = document.getText(range);
// Check if the setting to activate the linter is set to true.
const workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
const enableLinter: boolean = Workspace.getConfiguration(
"sourcepawn",
workspaceFolder
).get<boolean>("enableLinter");
// Stop early if linter is disabled.
if (
text === "" ||
/\/\/linter=false/.test(text) ||
!enableLinter ||
extname(document.fileName) !== ".sp"
) {
compilerDiagnostics.set(document.uri, []);
return;
}
const tmpPath = join(
extensions.getExtension("Sarrus.sourcepawn-vscode").extensionPath,
"tmpCompiled.smx"
);
const tmpFile = join(__dirname, "temp.sp");
const spcomp =
Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
"SpcompPath"
) || "";
if (!spcomp) {
return;
}
// Get the previous instance of spcomp if it exists
let throttle = throttles[document.uri.path];
if (throttle === undefined) {
throttle = new TimeoutFunction();
throttles[document.uri.path] = throttle;
}
// Cancel the previous instance and start a new one.
throttle.cancel();
throttle.start(() => {
const mainPath = findMainPath(document.uri);
// Separate the cases if we are using mainPath or not.
let scriptingFolder: string;
let filePath: string;
if (mainPath !== undefined && mainPath !== "") {
scriptingFolder = dirname(mainPath);
filePath = mainPath;
} else {
scriptingFolder = dirname(document.uri.fsPath);
let file = openSync(tmpFile, "w", 0o765);
writeSync(file, document.getText());
closeSync(file);
filePath = tmpFile;
}
// Generate compiler arguments.
const compilerArgs = [
"-i" +
Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
"SourcemodHome"
) || "",
"-i" + scriptingFolder,
"-i" + join(scriptingFolder, "include"),
"-v0",
filePath,
"-o" + tmpPath,
];
// Add a space at the beginning of every element, for security.
Workspace.getConfiguration("sourcepawn", workspaceFolder)
.get<string[]>("linterCompilerOptions")
.forEach((e) => compilerArgs.push(" " + e));
// Add the optional includes folders.
getAllPossibleIncludeFolderPaths(document.uri, true).forEach((e) =>
compilerArgs.push(`-i${e}`)
);
// Run the blank compile.
execFile(spcomp, compilerArgs, (error, stdout) => {
// If it compiled successfully, delete the temporary files.
if (!error) {
unlink(tmpPath, (err) => {
if (err) {
console.error(err);
}
});
}
parseSPCompErrors(
stdout,
compilerDiagnostics,
mainPath === undefined ? document.uri.fsPath : undefined
);
});
}, 300);
}
Example #7
Source File: http-server.ts From sdkgen with MIT License | 4 votes |
private attachRestHandlers() {
function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
}
for (const op of this.apiConfig.ast.operations) {
for (const ann of op.annotations) {
if (!(ann instanceof RestAnnotation)) {
continue;
}
if (!this.hasSwagger) {
setupSwagger(this);
this.hasSwagger = true;
}
const pathFragments = ann.path.split(/\{\w+\}/u);
let pathRegex = "^";
for (let i = 0; i < pathFragments.length; ++i) {
if (i > 0) {
pathRegex += "([^/]+?)";
}
pathRegex += escapeRegExp(pathFragments[i]);
}
pathRegex += "/?$";
for (const header of ann.headers.keys()) {
this.addHeader("Access-Control-Allow-Headers", header.toLowerCase());
}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.addHttpHandler(ann.method, new RegExp(pathRegex, "u"), async (req, res, body) => {
try {
const args: Record<string, unknown> = {};
const files: ContextRequest["files"] = [];
const { pathname, query } = parseUrl(req.url ?? "");
const match = pathname?.match(pathRegex);
if (!match) {
res.statusCode = 404;
return;
}
const simpleArgs = new Map<string, string | null>();
for (let i = 0; i < ann.pathVariables.length; ++i) {
const argName = ann.pathVariables[i];
const argValue = match[i + 1];
simpleArgs.set(argName, argValue);
}
const parsedQuery = query ? parseQuerystring(query) : {};
for (const argName of ann.queryVariables) {
const argValue = parsedQuery[argName] ?? null;
if (argValue === null) {
continue;
}
simpleArgs.set(argName, Array.isArray(argValue) ? argValue.join("") : argValue);
}
for (const [headerName, argName] of ann.headers) {
const argValue = req.headers[headerName.toLowerCase()] ?? null;
if (argValue === null) {
continue;
}
simpleArgs.set(argName, Array.isArray(argValue) ? argValue.join("") : argValue);
}
if (!ann.bodyVariable && req.headers["content-type"]?.match(/^application\/x-www-form-urlencoded/iu)) {
const parsedBody = parseQuerystring(body.toString());
for (const argName of ann.queryVariables) {
const argValue = parsedBody[argName] ?? null;
if (argValue === null) {
continue;
}
simpleArgs.set(argName, Array.isArray(argValue) ? argValue.join("") : argValue);
}
} else if (!ann.bodyVariable && req.headers["content-type"]?.match(/^multipart\/form-data/iu)) {
const busboy = Busboy({ headers: req.headers });
const filePromises: Array<Promise<void>> = [];
busboy.on("field", (field, value) => {
if (ann.queryVariables.includes(field)) {
simpleArgs.set(field, `${value}`);
}
});
busboy.on("file", (_field, stream, info) => {
const tempName = randomBytes(32).toString("hex");
const writeStream = createWriteStream(tempName);
filePromises.push(
new Promise((resolve, reject) => {
writeStream.on("error", reject);
writeStream.on("close", () => {
const contents = createReadStream(tempName);
files.push({ contents, name: info.filename });
contents.on("open", () => {
unlink(tempName, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
writeStream.on("open", () => {
stream.pipe(writeStream);
});
}),
);
});
await new Promise((resolve, reject) => {
busboy.on("finish", resolve);
busboy.on("error", reject);
busboy.write(body);
});
await Promise.all(filePromises);
} else if (ann.bodyVariable) {
const argName = ann.bodyVariable;
const arg = op.args.find(x => x.name === argName);
if (/application\/json/iu.test(req.headers["content-type"] ?? "")) {
args[argName] = JSON.parse(body.toString());
} else if (arg) {
let { type } = arg;
let solved = false;
if (type instanceof OptionalType) {
if (body.length === 0) {
args[argName] = null;
solved = true;
} else {
type = type.base;
}
}
if (!solved) {
if (
type instanceof BoolPrimitiveType ||
type instanceof IntPrimitiveType ||
type instanceof UIntPrimitiveType ||
type instanceof FloatPrimitiveType ||
type instanceof StringPrimitiveType ||
type instanceof DatePrimitiveType ||
type instanceof DateTimePrimitiveType ||
type instanceof MoneyPrimitiveType ||
type instanceof BigIntPrimitiveType ||
type instanceof CpfPrimitiveType ||
type instanceof CnpjPrimitiveType ||
type instanceof UuidPrimitiveType ||
type instanceof HexPrimitiveType ||
type instanceof Base64PrimitiveType
) {
simpleArgs.set(argName, body.toString());
} else if (type instanceof BytesPrimitiveType) {
args[argName] = body.toString("base64");
} else {
args[argName] = JSON.parse(body.toString());
}
}
}
}
for (const [argName, argValue] of simpleArgs) {
const arg = op.args.find(x => x.name === argName);
if (!arg) {
continue;
}
let { type } = arg;
if (type instanceof OptionalType) {
if (argValue === null) {
args[argName] = null;
continue;
} else {
type = type.base;
}
} else if (argValue === null) {
args[argName] = argValue;
continue;
}
if (type instanceof BoolPrimitiveType) {
if (argValue === "true") {
args[argName] = true;
} else if (argValue === "false") {
args[argName] = false;
} else {
args[argName] = argValue;
}
} else if (type instanceof UIntPrimitiveType || type instanceof IntPrimitiveType || type instanceof MoneyPrimitiveType) {
args[argName] = parseInt(argValue, 10);
} else if (type instanceof FloatPrimitiveType) {
args[argName] = parseFloat(argValue);
} else {
args[argName] = argValue;
}
}
const ip = getClientIp(req);
if (!ip) {
throw new Error("Couldn't determine client IP");
}
const request: ContextRequest = {
args,
deviceInfo: {
fingerprint: null,
id: randomBytes(16).toString("hex"),
language: null,
platform: null,
timezone: null,
type: "rest",
version: null,
},
extra: {},
files,
headers: req.headers,
id: randomBytes(16).toString("hex"),
ip,
name: op.name,
version: 3,
};
await this.executeRequest(request, (ctx, reply) => {
try {
if (ctx) {
for (const [headerKey, headerValue] of ctx.response.headers.entries()) {
res.setHeader(headerKey, headerValue);
}
}
if (ctx?.response.statusCode) {
res.statusCode = ctx.response.statusCode;
}
if (reply.error) {
const error = this.makeResponseError(reply.error);
if (!ctx?.response.statusCode) {
res.statusCode = error.type === "Fatal" ? 500 : 400;
}
res.setHeader("content-type", "application/json");
res.write(JSON.stringify(error));
res.end();
return;
}
if (req.headers.accept === "application/json") {
res.setHeader("content-type", "application/json");
res.write(JSON.stringify(reply.result));
res.end();
} else {
let type = op.returnType;
if (type instanceof OptionalType) {
if (reply.result === null) {
if (!ctx?.response.statusCode) {
res.statusCode = ann.method === "GET" ? 404 : 204;
}
res.end();
return;
}
type = type.base;
}
if (
type instanceof BoolPrimitiveType ||
type instanceof IntPrimitiveType ||
type instanceof UIntPrimitiveType ||
type instanceof FloatPrimitiveType ||
type instanceof StringPrimitiveType ||
type instanceof DatePrimitiveType ||
type instanceof DateTimePrimitiveType ||
type instanceof MoneyPrimitiveType ||
type instanceof BigIntPrimitiveType ||
type instanceof CpfPrimitiveType ||
type instanceof CnpjPrimitiveType ||
type instanceof UuidPrimitiveType ||
type instanceof HexPrimitiveType ||
type instanceof Base64PrimitiveType
) {
res.setHeader("content-type", "text/plain");
res.write(`${reply.result}`);
res.end();
} else if (type instanceof HtmlPrimitiveType) {
res.setHeader("content-type", "text/html");
res.write(`${reply.result}`);
res.end();
} else if (type instanceof XmlPrimitiveType) {
res.setHeader("content-type", "text/xml");
res.write(`${reply.result}`);
res.end();
} else if (type instanceof BytesPrimitiveType) {
const buffer = Buffer.from(reply.result as string, "base64");
// eslint-disable-next-line @typescript-eslint/no-floating-promises
FileType.fromBuffer(buffer)
.then(fileType => {
res.setHeader("content-type", fileType?.mime ?? "application/octet-stream");
})
.catch(err => {
console.error(err);
res.setHeader("content-type", "application/octet-stream");
})
.then(() => {
res.write(buffer);
res.end();
})
.catch(() => {});
} else {
res.setHeader("content-type", "application/json");
res.write(JSON.stringify(reply.result));
res.end();
}
}
} catch (error) {
console.error(error);
if (!res.headersSent) {
res.statusCode = 500;
}
res.end();
}
});
} catch (error) {
console.error(error);
if (!res.headersSent) {
res.statusCode = 500;
}
res.end();
}
});
}
}
}