forked from nodeSolidServer/node-solid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathldp-copy.js
More file actions
65 lines (62 loc) · 2.11 KB
/
ldp-copy.js
File metadata and controls
65 lines (62 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module.exports = copy
const debug = require('./debug')
const fs = require('fs')
const mkdirp = require('fs-extra').mkdirp
const path = require('path')
const request = require('request')
/**
* Cleans up a file write stream (ends stream, deletes the file).
* @method cleanupFileStream
* @private
* @param stream {WriteStream}
*/
function cleanupFileStream (stream) {
let streamPath = stream.path
stream.destroy()
fs.unlinkSync(streamPath)
}
/**
* Performs an LDP Copy operation, imports a remote resource to a local path.
* @param copyToPath {String} Local path to copy the resource into
* @param copyFromUri {String} Location of remote resource to copy from
* @param callback {Function} Node error callback
*/
function copy (copyToPath, copyFromUri, callback) {
mkdirp(path.dirname(copyToPath), function (err) {
if (err) {
debug.handlers('COPY -- Error creating destination directory: ' + err)
return callback(
new Error('Failed to create the path to the destination resource: ' +
err))
}
var destinationStream = fs.createWriteStream(copyToPath)
.on('error', function (err) {
cleanupFileStream(this)
return callback(new Error('Error writing data: ' + err))
})
.on('finish', function () {
// Success
debug.handlers('COPY -- Wrote data to: ' + copyToPath)
callback()
})
request.get(copyFromUri)
.on('error', function (err) {
debug.handlers('COPY -- Error requesting source file: ' + err)
this.end()
cleanupFileStream(destinationStream)
return callback(new Error('Error writing data: ' + err))
})
.on('response', function (response) {
if (response.statusCode !== 200) {
debug.handlers('COPY -- HTTP error reading source file: ' +
response.statusMessage)
this.end()
cleanupFileStream(destinationStream)
let error = new Error('Error reading source file: ' + response.statusMessage)
error.statusCode = response.statusCode
return callback(error)
}
})
.pipe(destinationStream)
})
}