fs.cp Copies Directory Trees With Filters

Copy a directory tree with fs.cp using recursive and filter options, skipping scratch files while preserving the nested folder structure.

JavascriptCli Tooling

Code

javascriptsnippet
16 lines
import { mkdir, writeFile, cp, readdir } from 'node:fs/promises';

await mkdir('site/assets', { recursive: true });
await writeFile('site/index.html', '<h1>home</h1>');
await writeFile('site/assets/style.css', 'body { margin: 0 }');
await writeFile('site/skip-me.tmp', 'scratch data');

// recursive copies nested folders; filter drops anything ending in .tmp
await cp('site', 'dist', {
  recursive: true,
  filter: (src) => !src.endsWith('.tmp'),
});

console.log('dist:', (await readdir('dist')).sort());
console.log('dist/assets:', await readdir('dist/assets'));
console.log('tmp skipped:', !(await readdir('dist')).includes('skip-me.tmp'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

dist: [ 'assets', 'index.html' ]
dist/assets: [ 'style.css' ]
tmp skipped: true

Inside the snippet

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:fs/promises, a Node.js built-in, exposing mkdir, writeFile, cp, readdir.

Watch out for

  • The only import, node:fs/promises, is part of the Node.js standard library.

Using it

The demo output is labeled (dist:, dist/assets:, tmp skipped:), so every printed line maps back to its originating operation.

Key statements

await writeFile('site/assets/style.css', 'body { margin: 0 }');
await writeFile('site/index.html', '<h1>home</h1>');
await writeFile('site/skip-me.tmp', 'scratch data');

Interactive Tools for This Topic

FAQ

Is the imported module an npm package?
No — `node:fs/promises` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.