Var extend = require ("extend "); Var fs = require ("fs "); Var excelExport = require ('excel-export '); Var guid = require ('guid '); Var path = require ('path '); Var excel = function (){ This. req = null; This. resp = null; }; /** * Generate an excel file * @ Param params */ Excel. prototype. createExcel = function (params ){ Var setting = {savePath: "uploadFile/excel /"}; Setting = extend ({}, setting, params ); Var uuid = guid. create (); Var data = params. data | ""; Var result = excelExport.exe cute (data ); Var name='excel'{uid='.xlsx '; Var filePath = path. resolve (setting. savePath, name ); Fs. writeFile (filePath, result, 'binary ', function (err ){ Setting. cb (filePath ); }); } /** * Calculate the last breakpoint information. * @ Param range * @ Returns {number} * @ Private */ Excel. prototype. _ calStartPosition = function (range ){ Var startPos = 0; If (typeof range! = 'Undefined '){ Var startPosMatch =/^ bytes = ([0-9] +)-$/. exec (range ); StartPos = Number (startPosMatch [1]); } Return startPos; } Excel. prototype. _ configHeader = function (config ){ Var startPos = config. startPos, FileSize = config. fileSize, Resp = this. resp; // If startPos is 0, the object is downloaded from 0; otherwise, the object is downloaded from a breakpoint. If (startPos = 0 ){ Resp. setHeader ('Accept-range', 'bytes '); } Else { Resp. setHeader ('content-range', 'bytes '+ startPos +'-'+ (fileSize-1) +'/'+ fileSize ); } Resp. writeHead (206, 'partial content ',{ 'Content-type': 'application/octet-stream' }); } Excel. prototype. _ init = function (filePath, down ){ Var config = {}; Var self = this; Fs. stat (filePath, function (error, state ){ If (error) Throw error; Config. fileSize = state. size; Var range = self. req. headers. range; Config. startPos = self. _ calStartPosition (range ); Self. config = config; Self. _ configHeader (config ); Down (); }); } /** * Download an object * @ Param filePath: file path * @ Param req * @ Param res * @ Param isDeleted: whether to delete the file after the download is complete. true: delete the file. */ Excel. prototype. download = function (filePath, req, res, isDeleted ){ Var self = this; Self. req = req; Self. resp = res; Path. exists (filePath, function (exist ){ If (exist ){ Self. _ init (filePath, function (){ Var config = self. config Resp = self. resp; FReadStream = fs. createReadStream (filePath ,{ Encoding: 'binary ', BufferSize: 1024*1024, Start: config. startPos, End: config. fileSize }); FReadStream. on ('data', function (chunk ){ Resp. write (chunk, 'binary '); }); FReadStream. on ('end', function (){ // Whether to delete the object If (isDeleted ){ Fs. unlink (filePath, function (err, res ){ }); } Resp. end (); }); }); } Else { Console. log ('the file does not exist! '); Return; } }); } Module. exports = new excel (); |