This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+12
View File
@@ -0,0 +1,12 @@
'use strict';
const NestedError = require('nested-error-stacks');
class CpFileError extends NestedError {
constructor(message, nested) {
super(message, nested);
Object.assign(this, nested);
this.name = 'CpFileError';
}
}
module.exports = CpFileError;
+78
View File
@@ -0,0 +1,78 @@
'use strict';
const {promisify} = require('util');
const fs = require('graceful-fs');
const makeDir = require('make-dir');
const pEvent = require('p-event');
const CpFileError = require('./cp-file-error');
const stat = promisify(fs.stat);
const lstat = promisify(fs.lstat);
const utimes = promisify(fs.utimes);
const chmod = promisify(fs.chmod);
exports.closeSync = fs.closeSync.bind(fs);
exports.createWriteStream = fs.createWriteStream.bind(fs);
exports.createReadStream = async (path, options) => {
const read = fs.createReadStream(path, options);
try {
await pEvent(read, ['readable', 'end']);
} catch (error) {
throw new CpFileError(`Cannot read from \`${path}\`: ${error.message}`, error);
}
return read;
};
exports.stat = path => stat(path).catch(error => {
throw new CpFileError(`Cannot stat path \`${path}\`: ${error.message}`, error);
});
exports.lstat = path => lstat(path).catch(error => {
throw new CpFileError(`lstat \`${path}\` failed: ${error.message}`, error);
});
exports.utimes = (path, atime, mtime) => utimes(path, atime, mtime).catch(error => {
throw new CpFileError(`utimes \`${path}\` failed: ${error.message}`, error);
});
exports.chmod = (path, mode) => chmod(path, mode).catch(error => {
throw new CpFileError(`chmod \`${path}\` failed: ${error.message}`, error);
});
exports.statSync = path => {
try {
return fs.statSync(path);
} catch (error) {
throw new CpFileError(`stat \`${path}\` failed: ${error.message}`, error);
}
};
exports.utimesSync = (path, atime, mtime) => {
try {
return fs.utimesSync(path, atime, mtime);
} catch (error) {
throw new CpFileError(`utimes \`${path}\` failed: ${error.message}`, error);
}
};
exports.makeDir = (path, options) => makeDir(path, {...options, fs}).catch(error => {
throw new CpFileError(`Cannot create directory \`${path}\`: ${error.message}`, error);
});
exports.makeDirSync = (path, options) => {
try {
makeDir.sync(path, {...options, fs});
} catch (error) {
throw new CpFileError(`Cannot create directory \`${path}\`: ${error.message}`, error);
}
};
exports.copyFileSync = (source, destination, flags) => {
try {
fs.copyFileSync(source, destination, flags);
} catch (error) {
throw new CpFileError(`Cannot copy from \`${source}\` to \`${destination}\`: ${error.message}`, error);
}
};
+91
View File
@@ -0,0 +1,91 @@
declare namespace cpFile {
interface Options {
/**
Overwrite existing destination file.
@default true
*/
readonly overwrite?: boolean;
/**
[Permissions](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation) for created directories.
It has no effect on Windows.
@default 0o777
*/
readonly directoryMode?: number;
}
interface ProgressData {
/**
Absolute path to source.
*/
sourcePath: string;
/**
Absolute path to destination.
*/
destinationPath: string;
/**
File size in bytes.
*/
size: number;
/**
Copied size in bytes.
*/
writtenBytes: number;
/**
Copied percentage, a value between `0` and `1`.
*/
percent: number;
}
interface ProgressEmitter {
/**
Note: For empty files, the `progress` event is emitted only once.
*/
on(event: 'progress', handler: (data: ProgressData) => void): Promise<void>;
}
}
declare const cpFile: {
/**
Copy a file.
@param source - The file you want to copy.
@param destination - Where you want the file copied.
@returns A `Promise` that resolves when the file is copied.
@example
```
import cpFile = require('cp-file');
(async () => {
await cpFile('source/unicorn.png', 'destination/unicorn.png');
console.log('File copied');
})();
```
*/
(source: string, destination: string, options?: cpFile.Options): Promise<void> & cpFile.ProgressEmitter;
/**
Copy a file synchronously.
@param source - The file you want to copy.
@param destination - Where you want the file copied.
@example
```
import cpFile = require('cp-file');
cpFile.sync('source/unicorn.png', 'destination/unicorn.png');
```
*/
sync(source: string, destination: string, options?: cpFile.Options): void;
};
export = cpFile;
+111
View File
@@ -0,0 +1,111 @@
'use strict';
const path = require('path');
const {constants: fsConstants} = require('fs');
const pEvent = require('p-event');
const CpFileError = require('./cp-file-error');
const fs = require('./fs');
const ProgressEmitter = require('./progress-emitter');
const cpFileAsync = async (source, destination, options, progressEmitter) => {
let readError;
const stat = await fs.stat(source);
progressEmitter.size = stat.size;
const readStream = await fs.createReadStream(source);
await fs.makeDir(path.dirname(destination), {mode: options.directoryMode});
const writeStream = fs.createWriteStream(destination, {flags: options.overwrite ? 'w' : 'wx'});
readStream.on('data', () => {
progressEmitter.writtenBytes = writeStream.bytesWritten;
});
readStream.once('error', error => {
readError = new CpFileError(`Cannot read from \`${source}\`: ${error.message}`, error);
writeStream.end();
});
let shouldUpdateStats = false;
try {
const writePromise = pEvent(writeStream, 'close');
readStream.pipe(writeStream);
await writePromise;
progressEmitter.writtenBytes = progressEmitter.size;
shouldUpdateStats = true;
} catch (error) {
throw new CpFileError(`Cannot write to \`${destination}\`: ${error.message}`, error);
}
if (readError) {
throw readError;
}
if (shouldUpdateStats) {
const stats = await fs.lstat(source);
return Promise.all([
fs.utimes(destination, stats.atime, stats.mtime),
fs.chmod(destination, stats.mode)
]);
}
};
const cpFile = (sourcePath, destinationPath, options) => {
if (!sourcePath || !destinationPath) {
return Promise.reject(new CpFileError('`source` and `destination` required'));
}
options = {
overwrite: true,
...options
};
const progressEmitter = new ProgressEmitter(path.resolve(sourcePath), path.resolve(destinationPath));
const promise = cpFileAsync(sourcePath, destinationPath, options, progressEmitter);
promise.on = (...arguments_) => {
progressEmitter.on(...arguments_);
return promise;
};
return promise;
};
module.exports = cpFile;
const checkSourceIsFile = (stat, source) => {
if (stat.isDirectory()) {
throw Object.assign(new CpFileError(`EISDIR: illegal operation on a directory '${source}'`), {
errno: -21,
code: 'EISDIR',
source
});
}
};
module.exports.sync = (source, destination, options) => {
if (!source || !destination) {
throw new CpFileError('`source` and `destination` required');
}
options = {
overwrite: true,
...options
};
const stat = fs.statSync(source);
checkSourceIsFile(stat, source);
fs.makeDirSync(path.dirname(destination), {mode: options.directoryMode});
const flags = options.overwrite ? null : fsConstants.COPYFILE_EXCL;
try {
fs.copyFileSync(source, destination, flags);
} catch (error) {
if (!options.overwrite && error.code === 'EEXIST') {
return;
}
throw error;
}
fs.utimesSync(destination, stat.atime, stat.mtime);
};
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+64
View File
@@ -0,0 +1,64 @@
{
"name": "cp-file",
"version": "9.1.0",
"description": "Copy a file",
"license": "MIT",
"repository": "sindresorhus/cp-file",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && nyc ava && tsd"
},
"files": [
"cp-file-error.js",
"fs.js",
"index.js",
"index.d.ts",
"progress-emitter.js"
],
"keywords": [
"copy",
"cp",
"file",
"clone",
"fs",
"stream",
"file-system",
"ncp",
"fast",
"quick",
"data",
"content",
"contents"
],
"dependencies": {
"graceful-fs": "^4.1.2",
"make-dir": "^3.0.0",
"nested-error-stacks": "^2.0.0",
"p-event": "^4.1.0"
},
"devDependencies": {
"ava": "^2.1.0",
"clear-module": "^3.1.0",
"coveralls": "^3.0.4",
"del": "^5.1.0",
"import-fresh": "^3.0.0",
"nyc": "^15.0.0",
"sinon": "^9.0.0",
"tsd": "^0.11.0",
"uuid": "^7.0.2",
"xo": "^0.28.2"
},
"xo": {
"rules": {
"unicorn/string-content": "off"
}
}
}
+35
View File
@@ -0,0 +1,35 @@
'use strict';
const EventEmitter = require('events');
const writtenBytes = new WeakMap();
class ProgressEmitter extends EventEmitter {
constructor(sourcePath, destinationPath) {
super();
this._sourcePath = sourcePath;
this._destinationPath = destinationPath;
}
get writtenBytes() {
return writtenBytes.get(this);
}
set writtenBytes(value) {
writtenBytes.set(this, value);
this.emitProgress();
}
emitProgress() {
const {size, writtenBytes} = this;
this.emit('progress', {
sourcePath: this._sourcePath,
destinationPath: this._destinationPath,
size,
writtenBytes,
percent: writtenBytes === size ? 1 : writtenBytes / size
});
}
}
module.exports = ProgressEmitter;
+116
View File
@@ -0,0 +1,116 @@
# cp-file
> Copy a file
## Highlights
- Fast by using streams in the async version and [`fs.copyFileSync()`](https://nodejs.org/api/fs.html#fs_fs_copyfilesync_src_dest_flags) in the synchronous version.
- Resilient by using [graceful-fs](https://github.com/isaacs/node-graceful-fs).
- User-friendly by creating non-existent destination directories for you.
- Can be safe by turning off [overwriting](#optionsoverwrite).
- Preserves file mode, [but not ownership](https://github.com/sindresorhus/cp-file/issues/22#issuecomment-502079547).
- User-friendly errors.
## Install
```
$ npm install cp-file
```
## Usage
```js
const cpFile = require('cp-file');
(async () => {
await cpFile('source/unicorn.png', 'destination/unicorn.png');
console.log('File copied');
})();
```
## API
### cpFile(source, destination, options?)
Returns a `Promise` that resolves when the file is copied.
### cpFile.sync(source, destination, options?)
#### source
Type: `string`
The file you want to copy.
#### destination
Type: `string`
Where you want the file copied.
#### options
Type: `object`
##### overwrite
Type: `boolean`\
Default: `true`
Overwrite existing destination file.
##### directoryMode
Type: `number`\
Default: `0o777`
[Permissions](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation) for created directories.
It has no effect on Windows.
### cpFile.on('progress', handler)
Progress reporting. Only available when using the async method.
#### handler(data)
Type: `Function`
##### data
```js
{
sourcePath: string,
destinationPath: string,
size: number,
writtenBytes: number,
percent: number
}
```
- `source` and `destination` are absolute paths.
- `size` and `writtenBytes` are in bytes.
- `percent` is a value between `0` and `1`.
###### Notes
- For empty files, the `progress` event is emitted only once.
- The `.on()` method is available only right after the initial `cpFile()` call. So make sure
you add a `handler` before `.then()`:
```js
const cpFile = require('cp-file');
(async () => {
await cpFile(source, destination).on('progress', data => {
// …
});
})();
```
## Related
- [cpy](https://github.com/sindresorhus/cpy) - Copy files
- [cpy-cli](https://github.com/sindresorhus/cpy-cli) - Copy files on the command-line
- [move-file](https://github.com/sindresorhus/move-file) - Move a file
- [make-dir](https://github.com/sindresorhus/make-dir) - Make a directory and its parents if needed