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.
Code
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: trueInside 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.