/
CreateImage-node.coffee
108 lines (100 loc) · 2.6 KB
/
CreateImage-node.coffee
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
noflo = require 'noflo'
Canvas = require('noflo-canvas').canvas
Image = Canvas.Image
urlUtil = require 'url'
request = require 'request'
tmp = require 'tmp'
fs = require 'fs'
log = require 'graceful-logger'
# @runtime noflo-nodejs
# @name CreateImage
exports.getComponent = ->
c = new noflo.Component
c.description = 'Load image from URL or path and send node-canvas compatible image'
c.icon = 'picture-o'
c.inPorts.add 'url',
datatype: 'string'
description: 'Image URL'
c.inPorts.add 'crossorigin',
datatype: 'string'
description: 'not applicable to Node version'
required: false
c.outPorts.add 'image',
datatype: 'object'
description: 'Loaded image'
c.outPorts.add 'error',
datatype: 'object'
noflo.helpers.WirePattern c,
in: 'url'
params: 'crossorigin'
out: 'image'
forwardGroups: true
async: true
, (url, groups, out, callback) ->
onLoad = (err, image) ->
if err
onError err
return
out.beginGroup url
out.send image
out.endGroup()
do callback
return
onError = (err) ->
err.url = url
log.err err
return callback err
loadFile = (path) ->
fs.stat path, (err, stats) ->
return onError err if err
if stats.size is 0
e = new Error 'CreateImage: temporary file has zero size'
return onError e
fs.readFile path, (err, image) ->
if err
return onError err
img = new Image
img.onload = () ->
onLoad null, img
img.onerror = (err) ->
onError err, null
img.src = image
urlOptions = urlUtil.parse url
if urlOptions.protocol is 'data:'
img = new Image
img.onload = () ->
onLoad null, img
img.onerror = (err) ->
onError err, null
img.src = url
return
if urlOptions.protocol
# Remote image
tmpFile = tmp.fileSync()
stream = fs.createWriteStream tmpFile.name
req = request
url: url
timeout: 10000
req.pipe stream
error = null
req.on 'response', (resp) ->
return if resp.statusCode is 200
error = new Error "CreateImage: response status code is #{resp.statusCode}"
error.url = url
req.on 'error', (err) ->
err.url = url
error = err
req.on 'end', ->
if error
tmpFile.removeCallback()
onError error
return
try
loadFile tmpFile.name
catch e
tmpFile.removeCallback()
onError e
return
# Local image
loadFile url
return