回答編集履歴
2
修正コードの追加
test
CHANGED
@@ -49,3 +49,61 @@
|
|
49
49
|
- ネット非接続時などの失敗した時のエラー処理
|
50
50
|
- 非同期で実行
|
51
51
|
- バージョン管理
|
52
|
+
|
53
|
+
# 追加
|
54
|
+
|
55
|
+
エラー処理と非同期処理
|
56
|
+
|
57
|
+
```
|
58
|
+
const https = require('https')
|
59
|
+
const originalfs = require('original-fs')
|
60
|
+
|
61
|
+
/**
|
62
|
+
* http.get
|
63
|
+
* asarのダウンロード・置き換え
|
64
|
+
* @param {*} url ダウンロードするファイルのURL
|
65
|
+
* @param {*} outURL 出力するファイルのURL
|
66
|
+
*/
|
67
|
+
const asarDownLoad = async (url, outURL) => {
|
68
|
+
|
69
|
+
try {
|
70
|
+
return await new Promise((resolve, reject) => {
|
71
|
+
|
72
|
+
const req = https.get(url, async (res) => {
|
73
|
+
|
74
|
+
console.log(res.statusCode) // 303が返ってくる
|
75
|
+
console.log(res.statusMessage)
|
76
|
+
|
77
|
+
// 303だった場合locationを見てそこから取得
|
78
|
+
if (res.statusCode === 303) {
|
79
|
+
await asarDownLoad(res.headers.location, outURL) // 再帰
|
80
|
+
resolve(true) //trueを返す
|
81
|
+
return
|
82
|
+
}
|
83
|
+
// ダウンロードした内容をそのまま、ファイル書き出し。
|
84
|
+
const outFile = originalfs.createWriteStream(outURL)
|
85
|
+
res.pipe(outFile)
|
86
|
+
|
87
|
+
// 終わったらファイルストリームをクローズ。
|
88
|
+
res.on('end', () => {
|
89
|
+
console.log('end')
|
90
|
+
outFile.close()
|
91
|
+
resolve(true) // trueを返す
|
92
|
+
})
|
93
|
+
})
|
94
|
+
|
95
|
+
// エラーがあれば扱う。
|
96
|
+
req.on('error', (err) => {
|
97
|
+
console.log('Error: ', err)
|
98
|
+
reject(false) // falseを返す
|
99
|
+
})
|
100
|
+
})
|
101
|
+
} catch (err) { // rejectのfalseをキャッチ
|
102
|
+
console.log(err)
|
103
|
+
return err // falseを返す
|
104
|
+
}
|
105
|
+
|
106
|
+
}
|
107
|
+
|
108
|
+
exports.asarDownLoad = asarDownLoad
|
109
|
+
```
|
1
次することの追加
test
CHANGED
@@ -43,3 +43,9 @@
|
|
43
43
|
```
|
44
44
|
|
45
45
|
Google Driveだと`303`のステータスコードが返ってくるので、その場合は`res.headers.location`を`get()`の第一引数に渡してもう一度処理をする。
|
46
|
+
|
47
|
+
# これから検討すること
|
48
|
+
|
49
|
+
- ネット非接続時などの失敗した時のエラー処理
|
50
|
+
- 非同期で実行
|
51
|
+
- バージョン管理
|