fs#unlinkSync TypeScript Examples

The following examples show how to use fs#unlinkSync. 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: file-utils.ts    From plasmic with MIT License 7 votes vote down vote up
/**
 * Runs the search pattern through `glob` and deletes all resulting files
 * @param searchPattern - glob search query
 * @param skipPatterns - array of fragments. Skip any file contains any of the fragments
 */
export function deleteGlob(
  searchPattern: string,
  skipPatterns?: string[]
): void {
  const filesToDelete = glob
    .sync(searchPattern)
    .filter(
      (file) =>
        !skipPatterns || !skipPatterns.find((pattern) => file.includes(pattern))
    );
  filesToDelete.forEach((f: string) => unlinkSync(f));
}
Example #2
Source File: util.ts    From attranslate with MIT License 6 votes vote down vote up
export function deleteFile(path: string): void {
  checkExists(path);
  unlinkSync(path);
  console.info(`Deleted ${getDebugPath(path)}`);
}
Example #3
Source File: psql-builder.test.ts    From exercises.json with The Unlicense 6 votes vote down vote up
describe("Scripts", () => {
  afterEach(() => {
    try {
      unlinkSync(resolve(process.cwd(), "exercises-psql.sql"));
    } catch (e) {
      console.warn("Nothing to delete");
    }
  });

  describe("psql-builder", () => {
    test("it creates an exercises-psql.sql file in the root", async () => {
      await exec("npm run build:psql", { cwd: process.cwd() });
      expect(existsSync(resolve(process.cwd(), "exercises-psql.sql"))).toBe(
        true
      );
    });
  });
});
Example #4
Source File: terminal.ts    From vscode-cadence with Apache License 2.0 6 votes vote down vote up
// Deletes all Flow files from extension storage.
// TODO: This doesn't work right now due to permissions issue
// REF: https://github.com/dapperlabs/flow-go/issues/1726
export function resetStorage (ctx: ExtensionContext): void {
  const storagePath = ctx.storagePath // ref: deprecated
  if (storagePath === undefined) {
    return
  }

  try {
    unlinkSync(join(storagePath, FLOW_CONFIG_FILENAME))
    unlinkSync(join(storagePath, FLOW_DB_FILENAME))
  } catch (err) {
    if (err.code === 'ENOENT') {
      return
    }
    console.error('Error resetting storage: ', err)
  }
}
Example #5
Source File: createThumbnail.ts    From MDDL with MIT License 6 votes vote down vote up
handler = wrapAsyncHandler(
  async (
    event: FilesReceivedResponse,
  ): Promise<ThumbnailsGeneratedResponse> => {
    const { files: rawFiles } = event
    const files = rawFiles.filter((f) => f.order === 0)
    const documentLinks: DocumentThumbnailLink[] = []
    for (const file of files) {
      const { id, path, documentId, contentType } = file
      const downloadLocation = `/tmp/${id}`
      const thumbnailLocation = `/tmp/thumbnail-${id}.png`
      const thumbnailKey = `${path}-thumbnail`
      await downloadObject(path, downloadLocation)
      await createThumbnail(
        contentType as FileContentTypeEnum,
        downloadLocation,
        thumbnailLocation,
      )
      await uploadObject(thumbnailLocation, thumbnailKey, {
        ContentType: FileContentTypeEnum.ImagePng,
      })
      documentLinks.push({
        documentId,
        thumbnailKey,
      })
      unlinkSync(downloadLocation)
      unlinkSync(thumbnailLocation)
    }
    return { documentLinks }
  },
  {
    rethrowAfterCapture: true,
  },
)
Example #6
Source File: compare-pdf-to-snapshot.ts    From pdf-visual-diff with MIT License 6 votes vote down vote up
comparePdfToSnapshot = (
  pdf: string | Buffer,
  snapshotDir: string,
  snapshotName: string,
  { maskRegions, ...restOpts }: Partial<CompareOptions> = {},
): Promise<boolean> => {
  const dir = join(snapshotDir, snapshotsDirName)
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true })
  }

  const snapshotPath = join(dir, snapshotName + '.png')

  if (!existsSync(snapshotPath)) {
    return pdf2png(pdf)
      .then(maskImgWithRegions(maskRegions || []))
      .then(writeImages(snapshotPath))
      .then(() => true)
  }

  return pdf2png(pdf)
    .then(maskImgWithRegions(maskRegions || []))
    .then((images) =>
      compareImages(snapshotPath, images, restOpts).then((result) => {
        const diffSnapshotPath = join(dir, snapshotName + '.diff.png')
        if (result.equal) {
          if (existsSync(diffSnapshotPath)) {
            unlinkSync(diffSnapshotPath)
          }
          return true
        }

        const newSnapshotPath = join(dir, snapshotName + '.new.png')
        return writeImages(newSnapshotPath)(images)
          .then(() => writeImages(diffSnapshotPath)(result.diffs.map((x) => x.diff)))
          .then(() => false)
      }),
    )
}
Example #7
Source File: scripts-csv.test.ts    From attranslate with MIT License 6 votes vote down vote up
test("csv re-create", async () => {
  targetPaths.forEach((path) => {
    unlinkSync(join(sampleDir, path));
  });
  const output = await runSampleScript(testScript, [assetDir]);
  targetPaths.forEach((path) => {
    expect(output).toContain(
      `Write target ${getDebugPath(join(sampleDir, path))}`
    );
  });
});
Example #8
Source File: cpGHPages.ts    From fzstd with MIT License 6 votes vote down vote up
git.log({
  from: 'HEAD~1',
  to: 'HEAD'
}).then(async log => {
  const hash = log.latest.hash.slice(0, 7);
  await git.checkout('gh-pages');
  for (const f of readdirSync(to('.'))) {
    if (statSync(f).isFile())
      unlinkSync(to(f));
  }
  const files = readdirSync(to('dist'))
  for (const f of files) {
    copyFileSync(to('dist', f), to(f));
  }
  await git.add(files);
  await git.commit('Build demo from ' + hash);
  await git.checkout('master');
});
Example #9
Source File: TimelapseNotification.ts    From mooncord with MIT License 6 votes vote down vote up
protected async compressTimelapse(timelapseBuffer: Buffer, timelapseName: string) {
        const absolutePath = (this.configHelper.getTempPath().startsWith('..')) ? path.join(__dirname, this.configHelper.getTempPath()) : this.configHelper.getTempPath()
        const tempPath = path.join(absolutePath, timelapseName)
        const tempPathShort = path.join(absolutePath, `compressed-${timelapseName}`)
        let renderComplete = false

        logRegular(`Compress Timelapse: ${timelapseName}`)

        writeFileSync(tempPath, timelapseBuffer,{encoding: 'utf8', flag: 'w+'})

        this.ffmpegRender
            .addInput(tempPath)
            .noAudio()
            .output(tempPathShort)
            .outputOptions(this.ffmpegArguments)
            .on('end', async (stdout, stderr) => {
                renderComplete = true
            })

        this.ffmpegRender.run()

        await waitUntil(() => renderComplete === true, { timeout: Number.POSITIVE_INFINITY })

        logSuccess(`Compressed Timelapse: ${timelapseName}`)

        unlinkSync(tempPath)

        const timelapseRaw = readFileSync(tempPathShort)

        unlinkSync(tempPathShort)

        return timelapseRaw
    }
Example #10
Source File: server.ts    From omegga with ISC License 6 votes vote down vote up
async getSaveData(region?: {
    center: [number, number, number];
    extent: [number, number, number];
  }) {
    const saveFile =
      this._tempSavePrefix + Date.now() + '_' + this._tempCounter.save++;

    await this.saveBricksAsync(saveFile, region);

    // read the save file
    const savePath = this.getSavePath(saveFile);
    if (savePath) {
      // read and parse the save file
      const saveData = read(readFileSync(savePath));

      // delete the save file after we're done reading it
      unlinkSync(savePath);

      // return the parsed save
      return saveData;
    }

    return undefined;
  }
Example #11
Source File: testHelper.ts    From cli with Apache License 2.0 6 votes vote down vote up
newCommandHelper() {
    return {
      deleteSpecFile: () => {
        const specficicationFilePath = path.resolve(process.cwd(), 'specification.yaml');
        if (existsSync(specficicationFilePath)) {
          unlinkSync(specficicationFilePath);
        }
      }
    };
  }
Example #12
Source File: bot.ts    From Adachi-BOT with MIT License 6 votes vote down vote up
/* 清除缓存图片 */
	private clearImageCache( that: Adachi ) {
		const bot = that.bot;
		return function () {
			const files: string[] = bot.file.getDirFiles( "data/image", "root" );
			files.forEach( f => {
				const path: string = bot.file.getFilePath(
					`data/image/${ f }`, "root"
				);
				unlinkSync( path );
			} );
			bot.logger.info( "图片缓存已清空" );
		}
	}
Example #13
Source File: runBatch.ts    From elephize with MIT License 6 votes vote down vote up
function onData(basePath: string[], promises: Array<Promise<any>>, filename: string, content: string) {
  process.stdout.write('[data received] ' + filename + '\n');
  promises.push(new Promise((resolve) => {
    const resultFileName = join(baseDir, normalizeFileExt(filename));
    const cont = prettier.format(content, phpPrettierOptions);

    mkdirpSync(dirname(resultFileName));

    writeFileSync(resultFileName + '.result', cont, 'utf-8');
    expect(cont).toBeTruthy();
    expect(cont, 'Failed in file: ' + filename)
      .toEqual(prettier.format(readFileSync(resultFileName, 'utf-8'), phpPrettierOptions));
    process.stdout.write('[test ok] ' + filename.replace(pResolve(...basePath), '') + '\n');
    unlinkSync(resultFileName + '.result');
    resolve(null);
  }));
}
Example #14
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function cleanupTempPulumiProject(adapter: BaseAdapter) {
  return (host: Tree) => {
    const infraDir = join(adapter.project.root, 'infrastructure');
    unlinkSync(resolve(infraDir, '.gitignore'));
    unlinkSync(resolve(infraDir, 'index.ts'));
    unlinkSync(resolve(infraDir, 'tsconfig.json'));
    unlinkSync(resolve(infraDir, 'package.json'));

    return host;
  };
}
Example #15
Source File: AppImageUpdater.ts    From electron-differential-updater with MIT License 5 votes vote down vote up
protected doInstall(options: InstallOptions): boolean {
    const appImageFile = process.env.APPIMAGE!!
    if (appImageFile == null) {
      throw newError("APPIMAGE env is not defined", "ERR_UPDATER_OLD_FILE_NOT_FOUND")
    }

    // https://stackoverflow.com/a/1712051/1910191
    unlinkSync(appImageFile)

    let destination: string
    const existingBaseName = path.basename(appImageFile)
    // https://github.com/electron-userland/electron-builder/issues/2964
    // if no version in existing file name, it means that user wants to preserve current custom name
    if (path.basename(options.installerPath) === existingBaseName || !/\d+\.\d+\.\d+/.test(existingBaseName)) {
      // no version in the file name, overwrite existing
      destination = appImageFile
    }
    else {
      destination = path.join(path.dirname(appImageFile), path.basename(options.installerPath))
    }

    execFileSync("mv", ["-f", options.installerPath, destination])

    const env: any = {
      ...process.env,
      APPIMAGE_SILENT_INSTALL: "true",
    }

    if (options.isForceRunAfter) {
      spawn(destination, [], {
        detached: true,
        stdio: "ignore",
        env,
      })
        .unref()
    }
    else {
      env.APPIMAGE_EXIT_AFTER_INSTALL = "true"
      execFileSync(destination, [], {env})
    }
    return true
  }
Example #16
Source File: rewriteBuilds.ts    From fzstd with MIT License 5 votes vote down vote up
unlinkSync(esmIndex);
Example #17
Source File: db.ts    From cross-seed with Apache License 2.0 5 votes vote down vote up
export function dropDatabase(): void {
	db.data = emptyDatabase;
	db.write();
	unlinkSync(path.join(appDir(), "cache.json"));
	rimraf.sync(path.join(appDir(), "torrent_cache"));
}
Example #18
Source File: Options.ts    From tf2autobot with MIT License 5 votes vote down vote up
function cleanPath(p: string): void {
    if (existsSync(p)) {
        readdirSync(p).map(s => unlinkSync(path.join(p, s)));
        rmdirSync(p);
    }
}
Example #19
Source File: rest.spec.ts    From sdkgen with MIT License 5 votes vote down vote up
unlinkSync(`${__dirname}/api.ts`);
Example #20
Source File: fs.utlis.ts    From nestjs-pdf with MIT License 5 votes vote down vote up
export function rmFile(path: string) {
    unlinkSync(path);
}
Example #21
Source File: run.test.ts    From tbify with MIT License 5 votes vote down vote up
describe('run', () => {
  test('正确设置环境变量', async () => {
    const envFilePath = tmp.file()
    const jsFilePath = tmp.writeSync(`
      const fs = require('fs')
      fs.writeFileSync(
        ${JSON.stringify(envFilePath)},
        JSON.stringify(process.env, null, 2),
      )
    `)
    await run('node', [jsFilePath])
    expect(JSON.parse(readFileSync(envFilePath).toString())).toEqual(
      expect.objectContaining(await getTaobaoEnv(`http://127.0.0.1:${port}`)),
    )
    unlinkSync(envFilePath)
    unlinkSync(jsFilePath)
  })

  test('应继承退出码', async () => {
    const jsFilePath = tmp.writeSync(`
      process.exit(100)
    `)
    const exitCode = await run('node', [jsFilePath])
    expect(exitCode).toBe(100)
    unlinkSync(jsFilePath)
  })

  test('支持覆盖内部的环境变量值', async () => {
    process.env.PRISMA_ENGINES_MIRROR = 'https://my.mirror'
    const envFilePath = tmp.file()
    const jsFilePath = tmp.writeSync(`
      const fs = require('fs')
      fs.writeFileSync(
        ${JSON.stringify(envFilePath)},
        JSON.stringify(process.env, null, 2),
      )
    `)
    await run('node', [jsFilePath])
    expect(
      JSON.parse(readFileSync(envFilePath).toString()).PRISMA_ENGINES_MIRROR,
    ).toBe('https://my.mirror')
    unlinkSync(envFilePath)
    unlinkSync(jsFilePath)
  })
})
Example #22
Source File: time-series.service.ts    From aqualink-app with MIT License 5 votes vote down vote up
async uploadData(
    surveyPointDataRangeDto: SurveyPointDataRangeDto,
    sensor: SourceType,
    files: Express.Multer.File[],
    failOnWarning?: boolean,
  ) {
    if (!sensor || !Object.values(SourceType).includes(sensor)) {
      throw new BadRequestException(
        `Field 'sensor' is required and must have one of the following values: ${Object.values(
          SourceType,
        ).join(', ')}`,
      );
    }

    const { siteId, surveyPointId } = surveyPointDataRangeDto;

    await surveyPointBelongsToSite(
      siteId,
      surveyPointId,
      this.surveyPointRepository,
    );

    if (!files?.length) {
      throw new BadRequestException(
        'The upload must contain at least one file',
      );
    }

    const uploadResponse = await Bluebird.Promise.map(
      files,
      async ({ path, originalname, mimetype }) => {
        try {
          const ignoredHeaders = await uploadTimeSeriesData(
            path,
            originalname,
            siteId.toString(),
            surveyPointId.toString(),
            sensor,
            {
              siteRepository: this.siteRepository,
              sourcesRepository: this.sourcesRepository,
              surveyPointRepository: this.surveyPointRepository,
              timeSeriesRepository: this.timeSeriesRepository,
              dataUploadsRepository: this.dataUploadsRepository,
            },
            failOnWarning,
            mimetype as Mimetype,
          );
          return { file: originalname, ignoredHeaders, error: null };
        } catch (err: unknown) {
          const error = err as HttpException;
          return {
            file: originalname,
            ignoredHeaders: null,
            error: error.message,
          };
        } finally {
          // Remove file once its processing is over
          unlinkSync(path);
        }
      },
      {
        concurrency: 1,
      },
    );

    return uploadResponse;
  }
Example #23
Source File: project.spec.ts    From cli with Apache License 2.0 5 votes vote down vote up
mockedUnlinkSync = jest.mocked(unlinkSync)
Example #24
Source File: config.ts    From deskbluez with MIT License 5 votes vote down vote up
async delete() {
        unlinkSync(this.path);
    }
Example #25
Source File: trivy_wrapper.ts    From trivy-vscode-extension with Apache License 2.0 5 votes vote down vote up
run() {
        let outputChannel = this.outputChannel;
        this.outputChannel.appendLine("");
        this.outputChannel.appendLine("Running Trivy to update results");

        if (!this.checkTrivyInstalled()) {
            return;
        }

        var files = readdirSync(this.resultsStoragePath).filter(fn => fn.endsWith('_results.json') || fn.endsWith('_results.json.json'));
        files.forEach(file => {
            let deletePath = path.join(this.resultsStoragePath, file);
            unlinkSync(deletePath);
        });

        const binary = this.getBinaryPath();

        this.workingPath.forEach(workingPath => {
            let command = this.buildCommand(workingPath);
            this.outputChannel.appendLine(`command: ${command}`);

            var execution = child.spawn(binary, command);

            execution.stdout.on('data', function (data) {
                outputChannel.appendLine(data.toString());
            });

            execution.stderr.on('data', function (data) {
                outputChannel.appendLine(data.toString());
            });

            execution.on('exit', function (code) {
                if (code !== 0) {
                    vscode.window.showErrorMessage("Trivy failed to run");
                    return;
                };
                vscode.window.showInformationMessage('Trivy ran successfully, updating results');
                outputChannel.appendLine('Reloading the Findings Explorer content');
                setTimeout(() => { vscode.commands.executeCommand("trivy-vulnerability-scanner.refresh"); }, 250);
            });
        });

    }
Example #26
Source File: fs.ts    From playwright-fluent with MIT License 5 votes vote down vote up
deleteFile = (path: string): void => {
  if (fileExists(path)) {
    unlinkSync(path);
  }
}
Example #27
Source File: index.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export function describeCommand(
  description: string,
  func: (clauseFields: describeFunctionArgs) => void,
  options?: { configFileName?: string },
): void {
  describe(description, () => {
    const consoleMessages: string[] = []
    const configFileName = options?.configFileName
    const getNthLastMessage = (n: number) => consoleMessages[consoleMessages.length - n]
    const getLastMessage = () => consoleMessages[consoleMessages.length - 1]
    const hasMessageContaining = (substring: string) =>
      Boolean(consoleMessages.find(consoleMessage => consoleMessage.includes(substring)))
    const configFolderPath = join(__dirname, '..', 'testconfig')

    //set config environment variable
    process.env.SWARM_CLI_CONFIG_FOLDER = configFolderPath

    global.console.log = jest.fn(message => {
      consoleMessages.push(message)
    })
    global.console.error = jest.fn(message => {
      consoleMessages.push(message)
    })

    global.process.stdout.write = jest.fn(message => {
      if (typeof message === 'string') {
        consoleMessages.push(message)
      } else {
        consoleMessages.push(new TextDecoder().decode(message))
      }

      return true
    })

    jest.spyOn(process, 'exit').mockImplementation(() => {
      throw new Error('process.exit() was called.')
    })

    jest.spyOn(global.console, 'warn')

    //if own config is needed
    if (configFileName) {
      const fileName = `${configFileName}.json`
      const configFilePath = join(configFolderPath, fileName)

      //set config environment variable
      process.env.SWARM_CLI_CONFIG_FILE = fileName
      process.env.SWARM_CLI_CONFIG_FILE_PATH = configFilePath

      //remove config file if it exists
      if (existsSync(configFilePath)) unlinkSync(configFilePath)
    }

    beforeEach(() => {
      consoleMessages.length = 0
    })

    func({ consoleMessages, getNthLastMessage, getLastMessage, hasMessageContaining, configFolderPath })
  })
}
Example #28
Source File: testHelper.ts    From cli with Apache License 2.0 5 votes vote down vote up
deleteDummyContextFile(): void {
    if (existsSync(DEFAULT_CONTEXT_FILE_PATH)) { unlinkSync(DEFAULT_CONTEXT_FILE_PATH); }
  }
Example #29
Source File: scripts-po.test.ts    From attranslate with MIT License 5 votes vote down vote up
test("po re-create non-cached target", async () => {
  const removeTarget = nonCachedTarget;
  unlinkSync(join(sampleDir, removeTarget));
  const output = await runSampleScript(testScript, [assetDir]);
  expect(output).toContain(
    `Write target ${getDebugPath(join(sampleDir, removeTarget))}`
  );
});