Get an unused filename by appending a number if it exists: `file.txt` → `file (1).txt`
Installations
npm install unused-filename
Developer Guide
Typescript
Yes
Module System
ESM
Min. Node Version
^12.20.0 || ^14.13.1 || >=16.0.0
Node Version
16.14.0
NPM Version
8.3.2
Score
99.5
Supply Chain
99.5
Quality
75.5
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (93.84%)
TypeScript (6.16%)
Developer
sindresorhus
Download Statistics
Total Downloads
11,321,679
Last Day
12,163
Last Week
57,804
Last Month
360,421
Last Year
2,862,327
GitHub Statistics
141 Stars
21 Commits
9 Forks
5 Watching
1 Branches
6 Contributors
Bundle Size
1.67 kB
Minified
810.00 B
Minified + Gzipped
Sponsor this package
Package Meta Information
Latest Version
4.0.1
Package Id
unused-filename@4.0.1
Unpacked Size
12.33 kB
Size
3.57 kB
File Count
5
NPM Version
8.3.2
Node Version
16.14.0
Total Downloads
Cumulative downloads
Total Downloads
11,321,679
Last day
-63.6%
12,163
Compared to previous day
Last week
-58.1%
57,804
Compared to previous week
Last month
76.2%
360,421
Compared to previous month
Last year
-4.2%
2,862,327
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
unused-filename
Get an unused filename by appending a number if it exists:
file.txt
→file (1).txt
Useful for safely writing, copying, moving files without overwriting existing files.
Install
1npm install unused-filename
Usage
.
├── rainbow (1).txt
├── rainbow.txt
└── unicorn.txt
1import {unusedFilename} from 'unused-filename'; 2 3console.log(await unusedFilename('rainbow.txt')); 4//=> 'rainbow (2).txt'
API
unusedFilename(filePath, options?)
Returns a Promise<string>
containing either the original filename
or the filename
increment by options.incrementer
.
If an already incremented filePath
is passed, unusedFilename
will simply increment and replace the already existing index:
1import {unusedFilename} from 'unused-filename'; 2 3console.log(await unusedFilename('rainbow (1).txt')); 4//=> 'rainbow (2).txt'
unusedFilenameSync(filePath, options?)
Synchronous version of unusedFilename
.
filePath
Type: string
The path to check for filename collision.
options
Type: object
incrementer
Type: (filePath: string) => [string, string]
Default: Parentheses incrementer: file.txt
→ file (1).txt
A function that accepts a file path, and increments its index.
It's the incrementer's responsibility to extract an already existing index from the given file path so that it picks up and continues incrementing an already present index instead of appending a second one.
The incrementer has to return a tuple of [originalFilename, incrementedFilename]
, where originalFilename
is the filename without the index, and incrementedFilename
is a filename with input's index bumped by one.
1import {unusedFilename} from 'unused-filename'; 2 3// Incrementer that inserts a new index as a prefix. 4const prefixIncrementer = (filename, extension) => { 5 const match = filename.match(/^(?<index>\d+)_(?<originalFilename>.*)$/); 6 let {originalFilename, index} = match ? match.groups : {originalFilename: filename, index: 0}; 7 originalFilename = originalFilename.trim(); 8 return [`${originalFilename}${extension}`, `${++index}_${originalFilename}${extension}`]; 9}; 10 11console.log(await unusedFilename('rainbow.txt', {incrementer: prefixIncrementer})); 12//=> '1_rainbow.txt'
maxTries
Type: number
Default: Infinity
The maximum number of attempts to find an unused filename.
When the limit is reached, the function will throw MaxTryError
.
separatorIncrementer
Creates an incrementer that appends a number after a separator.
separatorIncrementer('_')
will increment file.txt
→ file_1.txt
.
Not all characters can be used as separators:
- On Unix-like systems,
/
is reserved. - On Windows,
<>:"/|?*
along with trailing periods are reserved.
1import {unusedFilename, separatorIncrementer} from 'unused-filename'; 2 3console.log(await unusedFilename('rainbow.txt', {incrementer: separatorIncrementer('_')})); 4//=> 'rainbow_1.txt'
MaxTryError
The error thrown when maxTries
limit is reached without finding an unused filename.
It comes with 2 custom properties:
originalPath
- Path without incrementation sequence.lastTriedPath
- The last tested incremented path.
Example:
1import {unusedFilename, MaxTryError} from 'unused-filename'; 2 3try { 4 const path = await unusedFilename('rainbow (1).txt', {maxTries: 0}); 5} catch (error) { 6 if (error instanceof MaxTryError) { 7 console.log(error.originalPath); // 'rainbow.txt' 8 console.log(error.lastTriedPath); // 'rainbow (1).txt' 9 } 10}
Related
- filenamify - Convert a string to a valid safe filename
![Empty State](/_next/static/media/empty.e5fae2e5.png)
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
0 existing vulnerabilities detected
Reason
Found 5/21 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/unused-filename/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/unused-filename/main.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:22
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 5 are checked with a SAST tool
Score
3.6
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More