|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const os = require('os'); |
| 5 | +const http = require('http'); |
| 6 | +const path = require('path'); |
| 7 | +const assert = require('assert'); |
| 8 | + |
| 9 | +const formidable = require('../../src/index'); |
| 10 | + |
| 11 | +const PORT = 13532; |
| 12 | +const DEFAULT_UPLOAD_DIR = path.join( |
| 13 | + os.tmpdir(), |
| 14 | + 'test-store-files-option-default', |
| 15 | +); |
| 16 | +const CUSTOM_UPLOAD_DIR = path.join( |
| 17 | + os.tmpdir(), |
| 18 | + 'test-store-files-option-custom', |
| 19 | +); |
| 20 | +const CUSTOM_UPLOAD_FILE_PATH = path.join(CUSTOM_UPLOAD_DIR, 'test-file'); |
| 21 | +const testFilePath = path.join( |
| 22 | + path.dirname(__dirname), |
| 23 | + 'fixture', |
| 24 | + 'file', |
| 25 | + 'binaryfile.tar.gz', |
| 26 | +); |
| 27 | + |
| 28 | +const server = http.createServer((req, res) => { |
| 29 | + if (!fs.existsSync(DEFAULT_UPLOAD_DIR)) { |
| 30 | + fs.mkdirSync(DEFAULT_UPLOAD_DIR); |
| 31 | + } |
| 32 | + if (!fs.existsSync(CUSTOM_UPLOAD_DIR)) { |
| 33 | + fs.mkdirSync(CUSTOM_UPLOAD_DIR); |
| 34 | + } |
| 35 | + const form = formidable({ |
| 36 | + uploadDir: DEFAULT_UPLOAD_DIR, |
| 37 | + fileWriteStreamHandler: () => fs.createWriteStream(CUSTOM_UPLOAD_FILE_PATH), |
| 38 | + }); |
| 39 | + |
| 40 | + form.parse(req, (err, fields, files) => { |
| 41 | + assert.strictEqual(Object.keys(files).length, 1); |
| 42 | + const { file } = files; |
| 43 | + |
| 44 | + assert.strictEqual(file.size, 301); |
| 45 | + assert.ok(file.path === undefined); |
| 46 | + |
| 47 | + const dirFiles = fs.readdirSync(DEFAULT_UPLOAD_DIR); |
| 48 | + assert.ok(dirFiles.length === 0); |
| 49 | + |
| 50 | + const uploadedFileStats = fs.statSync(CUSTOM_UPLOAD_FILE_PATH); |
| 51 | + assert.ok(uploadedFileStats.size === file.size); |
| 52 | + |
| 53 | + fs.unlinkSync(CUSTOM_UPLOAD_FILE_PATH); |
| 54 | + res.end(); |
| 55 | + server.close(); |
| 56 | + }); |
| 57 | +}); |
| 58 | + |
| 59 | +server.listen(PORT, (err) => { |
| 60 | + const choosenPort = server.address().port; |
| 61 | + const url = `http://localhost:${choosenPort}`; |
| 62 | + console.log('Server up and running at:', url); |
| 63 | + |
| 64 | + assert(!err, 'should not have error, but be falsey'); |
| 65 | + |
| 66 | + const request = http.request({ |
| 67 | + port: PORT, |
| 68 | + method: 'POST', |
| 69 | + headers: { |
| 70 | + 'Content-Type': 'application/octet-stream', |
| 71 | + }, |
| 72 | + }); |
| 73 | + |
| 74 | + fs.createReadStream(testFilePath).pipe(request); |
| 75 | +}); |
0 commit comments