1.读取xlsx
文件依赖包:multiparty,XLSX,代码如下:
var multiparty = require('multiparty'); var XLSX = require("xlsx"); var form = new multiparty.Form(); function to_json(workbook,id){ // 获取 Excel 中所有表名,返回 ['sheet1', 'sheet2'] var sheetNames = workbook.SheetNames; sheetNames.forEach(function(sheetName) { //获取每个sheet的数据。 var worksheet = workbook.Sheets[sheetName]; var tempArray = XLSX.utils.sheet_to_json(worksheet); tempArray.forEach(function(ele){ //获取每一条记录 ele.state = ele.state || 0; ele.create_time = ele.modify_time = utils.formatDate(); ele.modify_user = username; }); result[sheetName] = tempArray; }); // 把所有数据都已经读取到内存中去了 return result; } form.parse(req, function(err, fields, files) { if(err){ throw new Error("form is error"); } /*{ "fileToUpload": [ { "fieldName": "fileToUpload", "originalFilename": "test.xlsx", "path": "/var/folders/tk/jwcqj5_x74lgdzfcdhv248x00000gn/T/TILXemNkWT5V2YoNDXpxnEeS.xlsx", "headers": { "content-disposition": "form-data; name="fileToUpload"; filename="test.xlsx"", "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, "size": 9389 } ] } */ var filename = files.fileToUpload[0].originalFilename; var suffixArray = filename.split('.'); var suffix = suffixArray[suffixArray.length - 1].toLowerCase(); if( suffix != "xlsx" && suffix != "xls"){ throw new Error("只能上传xlsx,xls格式的文件"); }else{ //服务器临时储存文件的路径 var filepath = files.fileToUpload[0].path; console.log("读取的xlsx文件路径为:"+filepath); var workbook = XLSX.readFile(filepath); var result = to_json(workbook,req.session.login_username); //删除服务器临时储存文件的路径 fs.unlink(filepath,function(err){ console.error(filepath + "文件删除失败!"+err); }); } });
2.遍历文件夹或者文件
依赖包rd
var rd = require('rd'); var fs = require("fs"); var dirname = '../user/5832323914/'; // rd.read(dirname, function (err, files) { // if (err) throw err; // console.log("files",files); // }); rd.eachSync(dirname, function (f, s) { // 每找到一个文件都会调用一次此函数 // 参数s是通过 fs.stat() 获取到的文件属性值 if(fs.statSync(f).isFile()){ console.log('file: %s', f); fs.readFile(f,'utf8',function(err,data){ if(err)console.log("err is",err) else{ // console.log("data is,",data.replace(" ","")); var tempObj = JSON.parse(data); console.log("data.length:",tempObj.length); } }); } });