How to remove a file in Node.js?

How to remove a file in Node.js?

In this article, we review a code snippet from Tsup source code that demonstrates how a file can be removed from file system using Node.js.

I was reading through the Tsup source code, specifically src/index.ts. You will find this below code in that file.

 const experimentalDtsTask = async () => {
  if (!options.dts && options.experimentalDts) {
    const exports = runTypeScriptCompiler(options)
    await runDtsRollup(options, exports)
  }
 }

runDtsRollup

runDtsRollup is defined in api-extractor.ts and has the below code:

export async function runDtsRollup(
  options: NormalizedOptions,
  exports?: ExportDeclaration[],
) {
  try {
    const start = Date.now()
    const getDuration = () => {
      return `${Math.floor(Date.now() - start)}ms`
    }
    logger.info('dts', 'Build start')

    if (!exports) {
      throw new Error('Unexpected internal error: dts exports is not define')
    }
    await cleanDtsFiles(options)
    for (const format of options.format) {
      await rollupDtsFiles(options, exports, format)
    }
    logger.success('dts', `⚡️ Build success in ${getDuration()}`)
  } catch (error) {
    handleError(error)
    logger.error('dts', 'Build error')
  }
}

My attention was drawn towards cleanDtsFiles function.

cleanDtsFiles

cleanDtsFiles is defined in api-extractor and has the below code:

async function cleanDtsFiles(options: NormalizedOptions) {
  if (options.clean) {
    await removeFiles(['**/*.d.{ts,mts,cts}'], options.outDir)
  }
}

cleanDtsFiles does not use any Node.js API yet. It instead calls removeFiles function based on a condition — options.clean

removeFiles

removeFiles is defined in a file named utils.ts and has the below code:

export async function removeFiles(patterns: string[], dir: string) {
  const files = await glob(patterns, {
    cwd: dir,
    absolute: true,
  })
  files.forEach((file) => fs.existsSync(file) && fs.unlinkSync(file))
}

This function has two parameters:

  • patters: An array of strings

  • dir: A directory path

glob is imported from “tinyglobby” found at line 6. Read more about tinyglobby.

Once you get the files, using forEach, each file is looped through. fs.existsSync returns true if a path exists. Read more about fs.existsSync.

fs.unlinkSync synchronously unlinks a file, Read more about fs.unlinkSync and unlink means delete a name and possibly the file it refers
to — from Linux manual page.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at

My Github — https://github.com/ramu-narasinga

My website — https://ramunarasinga.com

My Youtube channel — https://www.youtube.com/@thinkthroo

Learning platform — https://thinkthroo.com

Codebase Architecture — https://app.thinkthroo.com/architecture

Best practices — https://app.thinkthroo.com/best-practices

Production-grade projects — https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/egoist/tsup/blob/main/src/index.ts#L200

  2. https://github.com/egoist/tsup/blob/main/src/api-extractor.ts#L172

  3. https://github.com/egoist/tsup/blob/main/src/utils.ts#L74

  4. https://www.npmjs.com/package/tinyglobby