node-file-handler.ts
3.03 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { NodeFileHandler } from '../../../src/file-handler/node-file-handler';
import * as http from 'http';
import * as https from 'https';
import * as fs from 'fs';
describe("Node Downloader", () => {
let nodeFileHandler = new NodeFileHandler();
beforeEach(() => {
nodeFileHandler.removeAllListeners();
});
it("should retrieve right handler", () => {
let httpHandler = nodeFileHandler.selectProtocol("http://someurl.com/image.jpg");
expect(httpHandler).toEqual(http);
let httpsHandler = nodeFileHandler.selectProtocol("https://someurl.com/image.jpg");
expect(httpsHandler).toEqual(https);
let nullHandler = nodeFileHandler.selectProtocol("notsupported://blub");
expect(nullHandler).toBeNull();
});
it("should download sample image from https source and store with new name", (done) => {
let source = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/800px-FullMoon2010.jpg";
let target = "./.tmp/full-moon-" + (new Date()).getTime() + ".jpg";
let lastProgress = 0;
nodeFileHandler
.on('progress', (progress: number) => {
expect(progress).toBeGreaterThan(lastProgress);
lastProgress = progress;
})
.once('error', (error) => {})
.once('complete', () => {
expect(lastProgress).toEqual(1);
expect(fs.existsSync(target)).toBeTruthy();
done();
})
.download(source, target);
});
it('should not download if file with same name exists and bytesize > 0', (done) => {
let source = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/800px-FullMoon2010.jpg";
let target = "./.tmp/full-moon-sensless.jpg";
let lastProgress = 0;
let file = fs.createWriteStream(target, {'flags': 'a'});
let dummyData = "some sensless information to fill bytes...";
file.write(new Buffer(dummyData));
file.end(() => {
nodeFileHandler
.on('progress', () => { fail("progress should not be called"); })
.once('error', () => {})
.once('complete', () => {
expect(fs.existsSync(target)).toBeTruthy();
done();
})
.download(source, target);
});
});
it('should correctly cleanup files', () => {
let basePath = "./.tmp-files";
fs.mkdirSync(basePath);
fs.writeFileSync(basePath + "/file1", "some data for file 1");
fs.writeFileSync(basePath + "/file2", "some data for file 2");
fs.writeFileSync(basePath + "/file3", "some data for file 3");
fs.writeFileSync(basePath + "/file4", "some data for file 4");
nodeFileHandler.cleanup([
{ source : '' , target : 'file1' },
{ source : '' , target : 'file2' }], basePath);
let files = fs.readdirSync(basePath);
expect(files.length).toEqual(2);
});
});