Best JavaScript code snippet using best
video-encoders.js
Source:video-encoders.js
1var exec = require('child_process').exec,2 spawn = require('child_process').spawn,3 path = require('path');4var initEncode = function initEncode(uploadDir, fileNoExt, originalExt, type) {5 return new Promise((resolve, reject) => {6 if(type === 'h264' || type === 'mpeg') {7 encodeVideoH264(uploadDir, fileNoExt, originalExt, null).then(8 (output) => { 9 resolve(output) 10 }, 11 (err) => { 12 console.log(err)13 reject(err) }14 )15 } else {16 encodeVideoVP9(uploadDir, fileNoExt, originalExt, null).then(17 (output) => { resolve(output) }, 18 (err) => { reject(err) }19 )20 }21 })22}23/**24* @Function encode video (extension || size)25* @param vidExt : video extension26* @param videoSize : the video size27* 28*/29var encodeVideoH264 = function encodeVideoH264(uploadDir, fileNoExt, originalExt, resolution) {30 return new Promise((resolve, reject) => {31 /**32 * -i input.mov: this is our input video file33 * -s 640x360: we tell FFmpeg to resize our input file to 640x360 while transcoding34 * -c:v libx264: we tell FFmpeg to use x264 as the video encoding library35 * -b:v 650k: the target video bitrate should be 650 kbps36 * -r 24: we want a constant framerate at 24 fps (which is the same as our source video file in this case)37 * -x264opts keyint=48:min-keyint=48:no-scenecut: we should have one keyframe every 48 frames (every 2 seconds). The keyframe injection should be constant38 * -profile:v main: we want H.264 main profile which is supported by most devices on the market while offering good transcoding quality and options39 * -preset fast: we use a fast preset for x264 transcoding40 * -movflags +faststart: the file should be web ready (moov box before mdat box)41 * -c:a libfdk_aac: we use libfdk_aac as our audio encoding library42 * -b:a 128k: the target audio bitrate should be 128 kbps43 * -ac 2: we want a stereo (2 audio channels) output44 * out-low.mp4: our output file should be a MP4 file named out-low.mp445 */46 // const cmd = "ffmpeg -i input.mov -s 640x360 -c:v libx264 "+47 // "-b:v 650k -r 24 -x264opts keyint=48:min-keyint=48:no-scenecut "+ 48 // "-profile:v main -preset fast -movflags +faststart -c:a libfdk_aac "+49 // "-b:a 128k -ac 2 out-low.mp4";50 var output, bitrate, bufsize;51 if(resolution === '640x360') { 52 output = 'out-low.mp4';53 bitrate = '650k';54 bufsize = '500k'55 } else if(resolution === '854x480') {56 output = 'out-med.mp4';57 bitrate = '1400k';58 bufsize = '1000k'59 } else if(resolution === '1280x720'){60 output = 'out-high.mp4'61 bitrate = '2500k'62 bufsize = '1500k'63 } else {64 output = 'output' + '.mp4'65 bitrate = '1400k'66 bufsize = '1000k'67 }68 var size = resolution !== null ? ' -s '+ resolution : ' ',69 cmd = ` ffmpeg -i ${uploadDir}/input.${originalExt} ` +70 ` -r 24 -c:a aac -b:a 128k -profile:v main ` +71 ` -ab 128k -f mp4 -aspect 16:9 -r 30 ${size} ` +72 ` -preset fast -movflags +faststart -ar 44100 ` +73 ` -c:v libx264 -x264opts keyint=24:min-keyint=24:no-scenecut ` +74 ` -b:v ${bitrate} -maxrate 1500k -bufsize ${bufsize} ` +75 //'-vf "scale=-1:720" ' +76 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', fileNoExt, output);77 /**78 * @process : spawn execute command79 * spawn('cmd.exe', ['/s', '/c', command]); : On Windows platform80 * spawn('/bin/sh', ['-c', command]); : On Unix platform81 */82 try {83 exec(cmd, { maxBuffer: 1024*500 }, (err, stdout, stderr) => {84 if(err) return reject(err)85 resolve(`${uploadDir}/${output}`)86 }) 87 } catch (e) {88 console.log('catch generate* error ', e)89 reject(e)90 } 91 })92}93/**94* @Function encode video (extension || size)95* @param vidExt : video extension96* @param videoSize : the video size97* 98*/99var encodeLibvorbis = function encodeLibvorbis(uploadDir, fileNoExt, originalExt) {100 return new Promise((resolve, reject) => {101 const cmd = `ffmpeg -i ${uploadDir}/input.${originalExt} ` +102 `-c:a libvorbis -b:a 128k -vn `+103 `-f webm -dash 1 `+104 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', fileNoExt, 'audio.webm');105 // path.join(__dirname, '..', '/optube', 'uploads', 'videos', fileNoExt, output) + 106 /**107 * @process : spawn execute command108 * spawn('cmd.exe', ['/s', '/c', command]); : On Windows platform109 * spawn('/bin/sh', ['-c', command]); : On Unix platform110 */111 try {112 exec(cmd, { maxBuffer: 1024*500 }, (err, stdout, stderr) => {113 if(err) return reject(err)114 resolve()115 }) 116 } catch (e) {117 console.log('catch generate* error ', e)118 reject(e)119 } 120 })121}122/**123* @Function encode video (extension || size)124* @param vidExt : video extension125* @param videoSize : the video size126* 127*/128var encodeVideoVP9 = function encodeVideoVP9(uploadDir, fileNoExt, originalExt, resolution) {129 return new Promise((resolve, reject) => {130 /**131 * -i input.mov: this is our input video file132 * -s 640x360: we tell FFmpeg to resize our input file to 640x360 while transcoding133 * -c:v libx264: we tell FFmpeg to use x264 as the video encoding library134 * -b:v 650k: the target video bitrate should be 650 kbps135 * -r 24: we want a constant framerate at 24 fps (which is the same as our source video file in this case)136 * -x264opts keyint=48:min-keyint=48:no-scenecut: we should have one keyframe every 48 frames (every 2 seconds). The keyframe injection should be constant137 * -profile:v main: we want H.264 main profile which is supported by most devices on the market while offering good transcoding quality and options138 * -preset fast: we use a fast preset for x264 transcoding139 * -movflags +faststart: the file should be web ready (moov box before mdat box)140 * -c:a libfdk_aac: we use libfdk_aac as our audio encoding library141 * -b:a 128k: the target audio bitrate should be 128 kbps142 * -ac 2: we want a stereo (2 audio channels) output143 * out-low.mp4: our output file should be a MP4 file named out-low.mp4144 */145 var output, bitrate, bufsize;146 if(resolution === '160x90') {147 output = 'out-min.webm';148 bitrate = '400k';149 bufsize = '300k'150 }else if(resolution === '640x360') { 151 output = 'out-low.webm';152 bitrate = '650k';153 bufsize = '500k'154 } else if(resolution === '854x480') {155 output = 'out-med.webm';156 bitrate = '1400k';157 bufsize = '1000k'158 } else if(resolution === '1280x720'){159 output = 'out-high.webm'160 bitrate = '2500k'161 bufsize = '1500k'162 } else {163 output = 'output.webm'164 bitrate = '1400k'165 bufsize = '1000k'166 }167 var size = resolution !== null ? ' -s '+ resolution : ' '168 const VP9_DASH_PARAMS ="-tile-columns 4 -frame-parallel 1"169 const cmd = `ffmpeg -i ${uploadDir}/input.${originalExt} -c:v libvpx-vp9 ` +170 ` ${size} -b:v ${bitrate} -keyint_min 150 `+171 ` -g 150 ${VP9_DASH_PARAMS} -an -f webm -dash 1 `+172 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', fileNoExt, output);173 /**174 * @process : spawn execute command175 * spawn('cmd.exe', ['/s', '/c', command]); : On Windows platform176 * spawn('/bin/sh', ['-c', command]); : On Unix platform177 */178 try {179 exec(cmd, { maxBuffer: 1024*500 }, (err, stdout, stderr) => {180 console.log('command line executed with code ', cmd)181 if(err) {182 console.log('maxBuffer', err)183 reject(err)184 }185 else { 186 resolve(`${uploadDir}/${output}`)187 }188 }) 189 } catch (e) {190 console.log('catch generate* error ', e)191 reject(e)192 } 193 })194}195var createDASHWebm = function createDASHWebm(uploadDir, fileNoExt, originalExt, nbResolution) {196 return new Promise((resolve, reject) => {197 var cmd = '';198 if(nbResolution === null) 199 cmd = dashWebmForNullCommand(uploadDir, fileNoExt)200 else if (nbResolution === 1)201 cmd = dashWebmForOneCommand(uploadDir, fileNoExt)202 else if (nbResolution === 2)203 cmd = dashWebmForTwoCommand(uploadDir, fileNoExt)204 else if (nbResolution === 3)205 cmd = dashWebmForThreeCommand(uploadDir, fileNoExt)206 else 207 cmd = dashWebmForFourCommand(uploadDir, fileNoExt) 208 /**209 * @process : spawn execute command210 * spawn('cmd.exe', ['/s', '/c', command]); : On Windows platform211 * spawn('/bin/sh', ['-c', command]); : On Unix platform212 */213 try {214 exec(cmd, { maxBuffer: 1024*500 }, (err, stdout, stderr) => {215 if(err) {216 console.log('maxBuffer', err)217 reject(err)218 }219 else { 220 resolve(`${uploadDir}/manifest_webm.mpd`)221 }222 }) 223 } catch (e) {224 console.log('catch generate* error ', e)225 reject(e)226 }227 })228}229var createDASHGpac = function createDASHGpac(uploadDir, fileNoExt, originalExt, nbResolution) {230 return new Promise((resolve, reject) =>{231 var inputs = '';232 if(nbResolution === null) 233 inputs = `${uploadDir}/output.mp4#audio ${uploadDir}/output.mp4#video`234 else if (nbResolution === 1) 235 inputs = `${uploadDir}/out-low.mp4#audio ${uploadDir}/out-low.mp4#video`236 else if (nbResolution === 2) 237 inputs = `${uploadDir}/out-med.mp4#audio ${uploadDir}/out-low.mp4#video ${uploadDir}/out-med.mp4#video`238 else 239 inputs = `${uploadDir}/out-high.mp4#audio ${uploadDir}/out-low.mp4#video ${uploadDir}/out-med.mp4#video ${uploadDir}/out-high.mp4#video`240 var cmd = 'MP4Box -dash 2000 -rap -frag-rap -bs-switching no ' +241 '-profile onDemand ' +242 '-out ' + path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', `${fileNoExt}`, 'manifest_mp4.mpd') + 243 ' ' + inputs 244 /**245 * @process : spawn execute command246 * spawn('cmd.exe', ['/s', '/c', command]); : On Windows platform247 * spawn('/bin/sh', ['-c', command]); : On Unix platform248 */249 try {250 exec(cmd, { maxBuffer: 1024*500 }, (err, stdout, stderr) => {251 if(err) return reject(err)252 resolve(uploadDir + '/manifest_mp4.mpd')253 }) 254 } catch (e) {255 console.log('catch generate* error ', e)256 reject(e)257 }258 })259}260var encodeVideosH264 = function encodeVideosH264(uploadDir, fileNoExt, originalExt, fileResolution) {261 return new Promise((resolve, reject) => {262 var width = fileResolution.w,263 height = fileResolution.h264 encodeVideoH264(uploadDir, fileNoExt, originalExt, '640x360').then(265 (res) => { 266 if(width >= 854 && height >= 480 ) {267 encodeVideoH264(uploadDir, fileNoExt, originalExt, '854x480').then(268 (res) => { 269 if(width >= 1280 && height >= 720 ) {270 encodeVideoH264(uploadDir, fileNoExt, originalExt, '1280x720').then(271 (res) => { resolve(3) }, 272 (err) => { reject(err) }273 )274 } else { 275 resolve(2) 276 }277 }, (err) => { reject(err) })278 } else {279 resolve(1)280 }281 }, (err) => { reject(err) } 282 )283 })284}285var encodeVideosVP9 = function encodeVideosVP9(uploadDir, fileNoExt, originalExt, fileResolution) {286 return new Promise((resolve, reject) => {287 var width = fileResolution.w,288 height = fileResolution.h289 encodeLibvorbis(uploadDir, fileNoExt, originalExt).then(290 () => {291 encodeVideoVP9(uploadDir, fileNoExt, originalExt, '160x90').then(292 (res) => { 293 if(width >= 640 && height >= 360 ) {294 encodeVideoVP9(uploadDir, fileNoExt, originalExt, '640x360').then(295 (res) => { 296 if(width >= 854 && height >= 480 ) {297 encodeVideoVP9(uploadDir, fileNoExt, originalExt, '854x480').then(298 (res) => { 299 if(width >= 1280 && height >= 720 ) {300 encodeVideoVP9(uploadDir, fileNoExt, originalExt, '1280x720').then(301 (res) => { resolve(4) }, 302 (err) => { reject(err) }303 )304 } else { 305 resolve(3) 306 }307 }, (err) => { reject(err) })308 } else {309 resolve(2)310 }311 }, (err) => { reject(err) } 312 )313 } else {314 resolve(1)315 }316 },317 (err) => { reject() }318 )319 }, 320 (err) => { reject() }321 )322 })323}324function dashWebmForNullCommand(uploadDir, fileNoExt) {325 return `ffmpeg -f webm_dash_manifest -i ${uploadDir}/output.webm `+326 ` -f webm_dash_manifest -i ${uploadDir}/audio.webm `+327 ` -c copy -map 0 -map 1 -f webm_dash_manifest `+328 ` -adaptation_sets "id=0,streams=0 id=1,streams=1" ` +329 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', `${fileNoExt}`, 'manifest_webm.mpd')330}331function dashWebmForOneCommand(uploadDir, fileNoExt) {332 return `ffmpeg -f webm_dash_manifest -i ${uploadDir}/out-min.webm `+333 ` -f webm_dash_manifest -i ${uploadDir}/audio.webm `+334 ` -c copy -map 0 -map 1 -f webm_dash_manifest `+335 ` -adaptation_sets "id=0,streams=0 id=1,streams=1" ` +336 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', `${fileNoExt}`, 'manifest_webm.mpd')337}338function dashWebmForTwoCommand(uploadDir, fileNoExt) {339 return `ffmpeg -f webm_dash_manifest -i ${uploadDir}/out-min.webm `+340 ` -f webm_dash_manifest -i ${uploadDir}/out-low.webm `+341 ` -f webm_dash_manifest -i ${uploadDir}/audio.webm `+342 ` -c copy -map 0 -map 1 -map 2-f webm_dash_manifest `+343 ` -adaptation_sets "id=0,streams=0,1 id=1,streams=2" ` +344 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', `${fileNoExt}`, 'manifest_webm.mpd')345}346function dashWebmForThreeCommand(uploadDir, fileNoExt) {347 return `ffmpeg -f webm_dash_manifest -i ${uploadDir}/out-min.webm `+348 ` -f webm_dash_manifest -i ${uploadDir}/out-low.webm `+349 ` -f webm_dash_manifest -i ${uploadDir}/out-med.webm `+350 ` -f webm_dash_manifest -i ${uploadDir}/audio.webm `+351 ` -c copy -map 0 -map 1 -map 2 -map 3 -f webm_dash_manifest `+352 ` -adaptation_sets "id=0,streams=0,1,2 id=1,streams=3" ` +353 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', `${fileNoExt}`, 'manifest_webm.mpd')354}355function dashWebmForFourCommand(uploadDir, fileNoExt) {356 return `ffmpeg -f webm_dash_manifest -i ${uploadDir}/out-min.webm `+357 ` -f webm_dash_manifest -i ${uploadDir}/out-low.webm `+358 ` -f webm_dash_manifest -i ${uploadDir}/out-med.webm `+359 ` -f webm_dash_manifest -i ${uploadDir}/out-high.webm `+360 ` -f webm_dash_manifest -i ${uploadDir}/audio.webm `+361 ` -c copy -map 0 -map 1 -map 2 -map 3 -map 4 -f webm_dash_manifest `+362 ` -adaptation_sets "id=0,streams=0,1,2,3 id=1,streams=1" ` +363 path.join(__dirname, '..', '..', '/optube', 'uploads', 'videos', `${fileNoExt}`, 'manifest_webm.mpd')364}365exports.initEncode = initEncode;366exports.createDASHWebm = createDASHWebm367exports.createDASHGpac = createDASHGpac368exports.encodeVideoVP9 = encodeVideoVP9369exports.encodeVideosVP9 = encodeVideosVP9370exports.encodeVideoH264 = encodeVideoH264371exports.encodeLibvorbis = encodeLibvorbis...
file.js
Source:file.js
1'use strict';2const EventEmitter = require('events').EventEmitter;3const util = require('util');4const fs = require('fs');5const path = require('path');6const mime = require('mime');7const mkdirSyncRecursively = require('./utils').mkdirSyncRecursively;8const createDirectoryIfNotExists = require('./utils')9 .createDirectoryIfNotExists;1011function SocketIOFile(socket, options) {12 if (!socket) {13 throw new Error('SocketIOFile requires Socket.');14 }1516 this.options = options || {};17 this.maxFileSize = +options.maxFileSize || undefined;18 this.accepts = options.accepts || [];19 this.chunkSize = +options.chunkSize || 10240;20 this.transmissionDelay = options.transmissionDelay || 0;21 this.overwrite = !!options.overwrite || false;22 this.rename = options.rename || null;23 this.resume = !!options.resume || false;2425 if (!options.uploadDir) {26 throw new Error('No upload directory specified.');27 }2829 // check directory is exists30 if (typeof options.uploadDir === 'string') {31 createDirectoryIfNotExists(options.uploadDir);32 } else if (typeof options.uploadDir === 'object') {33 for (var key in options.uploadDir) {34 createDirectoryIfNotExists(options.uploadDir[key]);35 }36 } else {37 throw new Error('options.uploadDir must be string or object array.');38 }3940 this.socket = socket;4142 socket.on('socket.io-file::reqSync', () => {43 socket.emit('socket.io-file::recvSync', {44 maxFileSize: this.maxFileSize,45 accepts: this.accepts,46 chunkSize: this.chunkSize,47 transmissionDelay: this.transmissionDelay,48 });4950 this.emit('ready');51 });5253 var self = this;54 var uploadingFiles = {};5556 socket.on('socket.io-file::createFile', (fileInfo) => {57 var id = fileInfo.id;58 var uploadDir = null;59 var uploadTo = fileInfo.uploadTo || '';60 var data = fileInfo.data || {};61 var filename = fileInfo.name;62 var originalFileName = fileInfo.name;6364 function sendError(err) {65 socket.emit(`socket.io-file::error::${id}`, {66 message: err.message,67 });68 self.emit('error', err, {69 uploadId: id,70 name: filename,71 uploadTo: uploadTo,72 data: data,73 });74 }7576 if (this.rename) {77 if (typeof this.rename === 'function') {78 filename = this.rename(filename, fileInfo);79 } else {80 filename = this.rename;81 }82 }8384 if (typeof options.uploadDir === 'string') {85 uploadDir = path.join(options.uploadDir, filename);86 } else if (typeof options.uploadDir === 'object') {87 if (!uploadTo) {88 return sendError(89 new Error(90 'Upload directory must be specified in multiple directories.'91 )92 );93 } else if (options.uploadDir[uploadTo]) {94 uploadDir = path.join(options.uploadDir[uploadTo], filename);95 } else {96 return sendError(97 new Error(98 'Upload directory ' + uploadTo + ' is not exists.'99 )100 );101 }102 } else if (fileInfo.size > this.maxFileSize) {103 return sendError(104 new Error(105 'Max Uploading File size must be under ' +106 this.maxFileSize +107 ' byte(s).'108 )109 );110 }111112 var startTime = new Date();113114 const emitObj = {115 name: filename,116 size: fileInfo.size,117 uploadDir: uploadDir,118 data: data,119 };120121 if (this.rename) {122 // rename setting123 // add origininalFileName to emitObj124 emitObj.originalFileName = originalFileName;125 }126127 this.emit('start', emitObj);128129 const uploadComplete = () => {130 const ws = uploadingFiles[id].writeStream;131132 if (ws) {133 ws.end();134 }135136 const endTime = new Date();137138 const mimeType = mime.lookup(uploadDir);139 const emitObj = {140 name: filename,141 size: uploadingFiles[id].size,142 wrote: uploadingFiles[id].wrote,143 uploadDir: uploadingFiles[id].uploadDir,144 data: uploadingFiles[id].data,145 mime: mimeType,146 estimated: endTime - startTime,147 uploadId: id,148 };149150 if (this.rename) {151 // rename setting152 // add originalFileName to emitObj153 emitObj.originalFileName = originalFileName;154 }155156 if (this.accepts && this.accepts.length > 0) {157 let found = false;158159 for (var i = 0; i < this.accepts.length; i++) {160 let accept = this.accepts[i];161162 if (mimeType === accept) {163 found = true;164 break;165 }166 }167168 // if mime is invalid, remove files and emit error169 if (!found) {170 fs.unlink(uploadDir); // no after works.171172 let err = new Error(173 'Not Acceptable file type ' +174 mimeType +175 ' of ' +176 filename +177 '. Type must be one of these: ' +178 this.accepts.join(', ')179 );180 return sendError(err);181 } else {182 self.socket.emit(183 `socket.io-file::complete::${id}`,184 emitObj185 );186 self.emit('complete', emitObj);187 }188 } else {189 self.socket.emit(`socket.io-file::complete::${id}`, emitObj);190 self.emit('complete', emitObj);191 }192193 // Release event handlers194 socket.removeAllListeners(`socket.io-file::stream::${id}`);195 socket.removeAllListeners(`socket.io-file::done::${id}`);196 socket.removeAllListeners(`socket.io-file::complete::${id}`);197 socket.removeAllListeners(`socket.io-file::abort::${id}`);198 socket.removeAllListeners(`socket.io-file::error::${id}`);199200 delete uploadingFiles[id];201 };202203 uploadingFiles[id] = {204 writeStream: null,205 name: fileInfo.name,206 size: fileInfo.size,207 wrote: 0,208 uploadDir: uploadDir,209 data: data,210 resume: false,211 };212213 // check if file exists214 const isFileExists = fs.existsSync(uploadDir);215216 if (isFileExists) {217 const uploadedFileStats = fs.statSync(uploadDir);218219 if (this.resume) {220 if (uploadingFiles[id].size > 0) {221 if (uploadingFiles[id].size > uploadedFileStats.size) {222 uploadingFiles[id].wrote = uploadedFileStats.size;223 uploadingFiles[id].resume = true;224 socket.emit(225 `socket.io-file::resume::${id}`,226 uploadingFiles[id]227 );228 } else {229 if (!this.overwrite) return uploadComplete();230 }231 }232 } else {233 if (!this.overwrite) return uploadComplete();234 }235 }236237 if (!options.overwrite) {238 let isFileExists = false;239240 try {241 fs.accessSync(uploadDir, fs.F_OK);242 isFileExists = true;243 } catch (e) {244 // console.log('File is not exists, so create new one.');245 }246247 if (isFileExists) return uploadComplete();248 }249250 var writeStream = fs.createWriteStream(uploadDir);251252 uploadingFiles[id].writeStream = writeStream;253254 socket.emit(`socket.io-file::request::${id}`);255256 socket.on(`socket.io-file::stream::${id}`, (chunk) => {257 if (uploadingFiles[id].abort) {258 socket.removeAllListeners(`socket.io-file::stream::${id}`);259 socket.removeAllListeners(`socket.io-file::done::${id}`);260 socket.removeAllListeners(`socket.io-file::complete::${id}`);261 socket.removeAllListeners(`socket.io-file::abort::${id}`);262 socket.removeAllListeners(`socket.io-file::error::${id}`);263264 uploadingFiles[id].writeStream.end();265 delete uploadingFiles[id];266 return;267 }268269 var writeStream = uploadingFiles[id].writeStream;270271 function write() {272 let result =273 uploadingFiles[id].wrote + chunk.length > self.maxFileSize;274275 if (276 uploadingFiles[id].wrote + chunk.length >277 self.maxFileSize278 ) {279 return sendError(280 new Error(281 `Uploading file size exceeded max file size ${self.maxFileSize} byte(s).`282 )283 );284 }285286 var writeDone = writeStream.write(chunk);287 uploadingFiles[id].wrote += chunk.length;288289 self.emit('stream', {290 name: uploadingFiles[id].name,291 size: uploadingFiles[id].size,292 wrote: uploadingFiles[id].wrote,293 uploadDir: uploadingFiles[id].uploadDir,294 data: uploadingFiles[id].data,295 uploadId: id,296 });297298 if (!writeDone) {299 writeStream.once('drain', () =>300 socket.emit(`socket.io-file::request::${id}`)301 );302 } else {303 if (self.transmissionDelay) {304 setTimeout(() => {305 socket.emit(`socket.io-file::request::${id}`);306 }, self.transmissionDelay);307 } else {308 socket.emit(`socket.io-file::request::${id}`);309 }310 }311 }312313 write();314 });315 socket.on(`socket.io-file::done::${id}`, () => {316 uploadComplete();317 });318 socket.on(`socket.io-file::abort::${id}`, () => {319 uploadingFiles[id].abort = true;320321 self.emit('abort', {322 name: uploadingFiles[id].name,323 size: uploadingFiles[id].size,324 wrote: uploadingFiles[id].wrote,325 uploadDir: uploadingFiles[id].uploadDir,326 data: uploadingFiles[id].data,327 uploadId: id,328 });329330 socket.emit(`socket.io-file::abort::${id}`, {331 name: uploadingFiles[id].name,332 size: uploadingFiles[id].size,333 wrote: uploadingFiles[id].wrote,334 uploadDir: uploadingFiles[id].uploadDir,335 });336 });337 });338}339340SocketIOFile.prototype.destroy = function () {341 this.emit('destroy');342 this.socket.emit('socket.io-file::disconnectByServer');343344 // Clear the resources345 this.removeAllListeners();346 this.socket = null; // Remove reference of Socket.io347};348util.inherits(SocketIOFile, EventEmitter);349
...
sharp.service.js
Source:sharp.service.js
1/* eslint no-unused-vars: off */2import sharp from 'sharp';3import path from 'path';4import fileUtils from '../utils/file.utils';5const validFormats = ['jpeg', 'png', 'webp'];6const convertImage = async (file, uploadDir, toFormat) => {7 if (validFormats.indexOf(toFormat) < 0) {8 return new Error(`Unable to convert Image: ${file} to format: ${toFormat}`);9 }10 try {11 return await sharp(file)12 .toFile(`${path.resolve(uploadDir, fileUtils.findFileName(file))}.${toFormat}`);13 } catch (error) {14 console.error(`Error occured while converting image ${file} to ${toFormat}, error: ${error}`);15 return new Error(`Error occured while converting image ${file} to ${toFormat}, error: ${error}`);16 }17};18const resizeImage = async (file, uploadDir, width, height) => {19 try {20 return await sharp(file)21 .resize(width, height)22 .toFile(`${path.resolve(uploadDir, fileUtils.findFileName(file))}.${fileUtils.findFileFormat(file)}`);23 } catch (error) {24 console.error(`Error occured while resizing image ${file} to ${width}*${height}, error: ${error}`);25 return new Error(`Error occured while resizing image ${file} to ${width}*${height}, error: ${error}`);26 }27};28const convertToPng = async (file, uploadDir) => {29 await convertImage(file, uploadDir, 'png');30};31const convertToJpeg = async (file, uploadDir) => {32 await convertImage(file, uploadDir, 'jpeg');33};34const convertToWebp = async (file, uploadDir) => {35 await convertImage(file, uploadDir, 'webp');36};37const convertTo360p = async (file, uploadDir) => {38 await resizeImage(file, uploadDir, 480, 360);39};40const convertTo480p = async (file, uploadDir) => {41 await resizeImage(file, uploadDir, 858, 480);42};43const convertTo720p = async (file, uploadDir) => {44 await resizeImage(file, uploadDir, 1280, 720);45};46const convertTo1080p = async (file, uploadDir) => {47 await resizeImage(file, uploadDir, 1920, 1080);48};49export default {50 convertToPng,51 convertToJpeg,52 convertToWebp,53 convertTo360p,54 convertTo480p,55 convertTo720p,56 convertTo1080p,...
Using AI Code Generation
1require_once '../vendor/autoload.php';2use BestServedCold\Upload\FileUpload;3$fileUpload = new FileUpload();4$fileUpload->uploadDir('/path/to/upload/directory');5$fileUpload->uploadFile('uploadedFile');6require_once '../vendor/autoload.php';7use BestServedCold\Upload\FileUpload;8$fileUpload = new FileUpload();9$fileUpload->uploadDir('/path/to/upload/directory');10$fileUpload->uploadFile('uploadedFile');11];12if ($fileUpload->validateFile($validationRules)) {13 echo 'File uploaded successfully!';14} else {15 echo 'File upload failed!';16}
Using AI Code Generation
1const BestLibrary = require('./BestLibrary');2const bestLibrary = new BestLibrary();3bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');4const BestLibrary = require('./BestLibrary');5const bestLibrary = new BestLibrary();6bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');7const BestLibrary = require('./BestLibrary');8const bestLibrary = new BestLibrary();9bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');10const BestLibrary = require('./BestLibrary');11const bestLibrary = new BestLibrary();12bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');13const BestLibrary = require('./BestLibrary');14const bestLibrary = new BestLibrary();15bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');16const BestLibrary = require('./BestLibrary');17const bestLibrary = new BestLibrary();18bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');19const BestLibrary = require('./BestLibrary');20const bestLibrary = new BestLibrary();21bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');22const BestLibrary = require('./BestLibrary');23const bestLibrary = new BestLibrary();24bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');25const BestLibrary = require('./BestLibrary');26const bestLibrary = new BestLibrary();27bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');28const BestLibrary = require('./BestLibrary');29const bestLibrary = new BestLibrary();30bestLibrary.uploadDir('C:\\Users\\user\\Desktop\\test');
Using AI Code Generation
1var BestHTTP = require('besthttp');2var http = new BestHTTP();3var filePath = 'C:\\Users\\user\\Desktop\\test.txt';4var fileName = 'test.txt';5var response = http.uploadFile(url, filePath, fileName);6console.log(response);7var BestHTTP = require('besthttp');8var http = new BestHTTP();9var filePath = 'C:\\Users\\user\\Desktop\\test.txt';10var response = http.downloadFile(url, filePath);11console.log(response);12var BestHTTP = require('besthttp');13var http = new BestHTTP();14var filePath = 'C:\\Users\\user\\Desktop\\test.txt';15var fileName = 'test.txt';16var response = http.uploadFile(url, filePath, fileName);17console.log(response);18var BestHTTP = require('besthttp');19var http = new BestHTTP();20var filePath = 'C:\\Users\\user\\Desktop\\test.txt';21var response = http.downloadFile(url, filePath);22console.log(response);23var BestHTTP = require('besthttp');24var http = new BestHTTP();25var filePath = 'C:\\Users\\user\\Desktop\\test.txt';26var fileName = 'test.txt';27var response = http.uploadFile(url, filePath, fileName);28console.log(response);29var BestHTTP = require('besthttp');30var http = new BestHTTP();31var filePath = 'C:\\Users\\user\\Desktop\\test.txt';32var response = http.downloadFile(url, filePath);33console.log(response);
Using AI Code Generation
1const BestZip = require('bestzip');2const fs = require('fs');3const path = require('path');4const testFolder = './test';5const testFolder2 = './test2';6const testFolder3 = './test3';7const testFolder4 = './test4';8const testFolder5 = './test5';9const testFolder6 = './test6';10const testFolder7 = './test7';11const testFolder8 = './test8';12const testFolder9 = './test9';13const testFolder10 = './test10';14const testFolder11 = './test11';15const testFolder12 = './test12';16const testFolder13 = './test13';17const testFolder14 = './test14';18const testFolder15 = './test15';19const testFolder16 = './test16';20const testFolder17 = './test17';21const testFolder18 = './test18';22const testFolder19 = './test19';23const testFolder20 = './test20';24const testFolder21 = './test21';25const testFolder22 = './test22';26const testFolder23 = './test23';27const testFolder24 = './test24';28const testFolder25 = './test25';29const testFolder26 = './test26';30const testFolder27 = './test27';31const testFolder28 = './test28';32const testFolder29 = './test29';33const testFolder30 = './test30';34const testFolder31 = './test31';35const testFolder32 = './test32';36const testFolder33 = './test33';37const testFolder34 = './test34';38const testFolder35 = './test35';39const testFolder36 = './test36';40const testFolder37 = './test37';41const testFolder38 = './test38';42const testFolder39 = './test39';43const testFolder40 = './test40';44const testFolder41 = './test41';45const testFolder42 = './test42';46const testFolder43 = './test43';47const testFolder44 = './test44';48const testFolder45 = './test45';49const testFolder46 = './test46';50const testFolder47 = './test47';51const testFolder48 = './test48';52const testFolder49 = './test49';53const testFolder50 = './test50';54const testFolder51 = './test51';55const testFolder52 = './test52';
Using AI Code Generation
1var BestHTTP = require("best-http");2var http = new BestHTTP();3var path = "C:/Users/BestHTTP/Desktop/test.txt";4var response = http.uploadDir(url, path);5console.log(response);6var BestHTTP = require("best-http");7var http = new BestHTTP();8var path = "C:/Users/BestHTTP/Desktop/";9var response = http.uploadDir(url, path);10console.log(response);11var BestHTTP = require("best-http");12var http = new BestHTTP();13var path = "C:/Users/BestHTTP/Desktop/test.txt";14var response = http.uploadDir(url, path, "test.txt");15console.log(response);16var BestHTTP = require("best-http");17var http = new BestHTTP();18var path = "C:/Users/BestHTTP/Desktop/test.txt";19var response = http.uploadDir(url, path, "test.txt", "application/octet-stream");20console.log(response);21var BestHTTP = require("best-http");22var http = new BestHTTP();23var path = "C:/Users/BestHTTP/Desktop/test.txt";24var response = http.uploadDir(url, path, "test.txt", "application/octet-stream", "utf-8");25console.log(response);26var BestHTTP = require("best-http");27var http = new BestHTTP();28var path = "C:/Users/BestHTTP/Desktop/test.txt";29var response = http.uploadDir(url, path, "test.txt", "application/octet-stream", "utf-8", 1000);30console.log(response);31var BestHTTP = require("best-http");
Using AI Code Generation
1var filePath = "C:/Users/John/Desktop/MyFile.txt";2var callback = function(err, res, body) {3 if(err) {4 console.log("Error: " + err);5 } else {6 console.log("Response: " + res.statusCode);7 console.log(body);8 }9};10var http = require("besthttp");11var http = new http();12http.uploadDir(url, filePath, callback);13var callback = function(err, res, body) {14 if(err) {15 console.log("Error: " + err);16 } else {17 console.log("Response: " + res.statusCode);18 console.log(body);19 }20};21var http = require("besthttp");22var http = new http();23http.uploadDir(url, filePath, callback);24The uploadDir() method is a wrapper around the request() method, so it can be used to upload a directory to the server as well. The uploadDir
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!