- Saved searches
- Use saved searches to filter your results more quickly
- License
- stdlib-js/fs-rename
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Rename A File With JavaScript In The Browser
- Updating the File Object
- Conclusion
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
License
stdlib-js/fs-rename
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
npm install @stdlib/fs-rename
- To load the package in a website via a script tag without installation and bundlers, use the ES Module available on the esm branch.
- If you are using Deno, visit the deno branch.
- For use in Observable, or in browser/node environments, use the Universal Module Definition (UMD) build available on the umd branch.
- To use as a general utility for the command line, install the corresponding CLI package globally.
The branches.md file summarizes the available branches and displays a diagram illustrating their relationships.
var rename = require( '@stdlib/fs-rename' );
rename( oldPath, newPath, clbk )
Asynchronously renames a file specified by oldPath to newPath .
var join = require( 'path' ).join; var oldPath = join( __dirname, 'examples', 'fixtures', 'file.txt' ); var newPath = join( __dirname, 'examples', 'fixtures', 'tmp.txt' ); rename( oldPath, newPath, done ); function done( error ) if ( error ) throw error; > >
rename.sync( oldPath, newPath )
Synchronously renames a file specified by oldPath to newPath .
var join = require( 'path' ).join; var oldPath = join( __dirname, 'examples', 'fixtures', 'file.txt' ); var newPath = join( __dirname, 'examples', 'fixtures', 'tmp.txt' ); var err = rename.sync( oldPath, newPath ); if ( err instanceof Error ) throw err; >
- oldPath can specify a directory. In this case, newPath must either not exist, or it must specify an empty directory.
- oldPath should not name an ancestor directory of newPath .
- If oldPath points to the pathname of a file that is not a directory, newPath should not point to the pathname of a directory.
- Write access permission is required for both the directory containing oldPath and the directory containing newPath .
- If the link named by newPath exists, newPath is removed and oldPath is renamed to newPath . The link named by newPath will remain visible to other threads throughout the renaming operation and refer to either the file referred to by newPath or to the file referred to by oldPath before the operation began.
- If oldPath and newPath resolve to either the same existing directory entry or to different directory entries for the same existing file, no action is taken, and no error is returned.
- If oldPath points to a pathname of a symbolic link, the symbolic link is renamed. If the newPath points to a pathname of a symbolic link, the symbolic link is removed.
- If a link named by newPath exists and the file’s link count becomes 0 when it is removed and no process has the file open, the space occupied by the file is freed and the file is no longer accessible. If one or more processes have the file open when the last link is removed, the link is removed before the function returns, but the removal of file contents is postponed until all references to the file are closed.
- The difference between rename.sync and fs.rename() is that fs.renameSync() will throw if an error is encountered (e.g., if given a non-existent path) and this API will return an error . Hence, the following anti-pattern
var fs = require( 'fs' ); // Check for path existence to prevent an error being thrown. if ( fs.existsSync( '/path/to/file.txt' ) ) fs.renameSync( '/path/to/file.txt', '/path/to/tmp.txt' ); >
var rename = require( '@stdlib/fs-rename' ); // Explicitly handle the error. var err = rename.sync( '/path/to/file.txt', '/path/to/tmp.txt' ); if ( err instanceof Error ) // You choose what to do. throw err; >
var join = require( 'path' ).join; var readFile = require( '@stdlib/fs-read-file' ).sync; var writeFile = require( '@stdlib/fs-write-file' ).sync; var exists = require( '@stdlib/fs-exists' ).sync; var unlink = require( '@stdlib/fs-unlink' ).sync; var rename = require( '@stdlib/fs-rename' ).sync; var src = join( __dirname, 'examples', 'fixtures', 'file.txt' ); var tmp = join( __dirname, 'examples', 'tmp.txt' ); var dest = join( __dirname, 'examples', 'foo.txt' ); // Create a temporary file: writeFile( tmp, readFile( src ) ); // Confirm that the temporary file exists: console.log( exists( tmp ) ); // => true // Rename the temporary file: rename( tmp, dest ); // Confirm that the renamed temporary file exists: console.log( exists( dest ) ); // => true // Remove the temporary file: unlink( dest ); // Confirm that the temporary file no longer exists: console.log( exists( dest ) ); // => false
To use as a general utility, install the CLI package globally
npm install -g @stdlib/fs-rename-cli
Usage: rename [options] Options: -h, --help Print this message. -V, --version Print the package version.
- Relative paths are resolved relative to the current working directory.
- Errors are written to stderr .
$ rename ./examples/fixtures/file.txt ./examples/fixtures/tmp.txt
- @stdlib/fs-exists : test whether a path exists on the filesystem.
- @stdlib/fs-read-file : read the entire contents of a file.
- @stdlib/fs-write-file : write data to a file.
- @stdlib/fs-unlink : remove a directory entry.
This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.
For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.
Rename A File With JavaScript In The Browser
A super concise tutorial on using JavaScript to rename files in the browser. We’ll quickly cover how to update a file object and read its contents. Let’s get started!
Updating the File Object
Let’s create a new file using the File constructor, we’ll then rename this file in a couple seconds.
const myFile = new File(['hello-world'], 'my-file.txt');
myFile.name = 'my-file-final-1-really.txt'; console.log(newFile); // Browser logs: File
Nope, didn’t work. Turns out we can’t update the name property of a file.
To rename a file we have to create a new file and pass our new name to the File constructor.
const myRenamedFile = new File([myFile], 'my-file-final-1-really.txt'); console.log(myRenamedFile); // Browser logs: File
To check if the file contents is the same we can read our file using the FileReader API.
const myReader = new FileReader(); myReader.readAsText(myRenamedFile); myReader.onload = () => console.log(myReader.result); // Browser logs: "hello-world"
Great, it has the same contents. ☀️
Surprise, this doesn’t work on Internet Explorer 11. ⛈
We can work around the age of IE11 by creating a Blob instead of a file object. Let’s create a tiny helper function that safely does this for us.
const createFile = (bits, name) => try // If this call fails, we go for Blob return new File(bits, name); > catch (e) // If we reach this point a new File could not be constructed var myBlob = new Blob(bits); myBlob.lastModified = new Date(); myBlob.name = name; return myBlob; > >;
Now we can safely create files like this:
const mySafeFile = createFile(['hello-world'], 'my-file.txt'); console.log(mySafeFile); // Modern browser logs: File // Internet Explorer logs: Blob
Note that the File constructor also takes a third “options” argument, this can contain the type of the file and the lastModified date of the file.
Let’s update our createFile function so it also supports the “options” argument.
const createFile = (bits, name, options) => try // If this fails, we go for Blob return new File(bits, name, options); > catch (e) // If we're here a new File could not be constructed var myBlob = new Blob(bits, options || >); myBlob.lastModified = new Date(); myBlob.name = name; return myBlob; > >;
Now we can create an actual plain/text file.
const myTextFile = createFile(['hello-world'], 'my-file.txt', type: 'plain/text', >);
A small caveat. Our files can now be of type Blob or File . When using the instanceof operator to test for types it’s best to test for Blob .
The following will be true on modern browsers but false on browsers that don’t support the File constructor (like Internet Explorer 11).
const testFile = createFile(['hello-world'], 'my-test.txt'); console.log(testFile instanceof File); // Modern browser logs: true // Internet Explorer logs: false
Testing for Blob instead of File will return the correct result on all browsers as File is a subclass of Blob .
const testFile = createFile(['hello-world'], 'my-test.txt'); console.log(testFile instanceof Blob); // Modern browser logs: true // Internet Explorer logs: true
Conclusion
We learned that updating a file object is not possible but that we can easily copy the contents of a file to a new file and give our new file a name.
To verify that the contents of the file was actually copied we took a quick look using the FileReader API.
Finally to help with cross browser compatibility we created a tiny function that can create a “File” object on all relevant browsers, “relevant” being relative.
I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there
At PQINA I design and build highly polished web components.
Make sure to check out FilePond a free file upload component, and Pintura an image editor that works on every device.