安装模块:package.json 添加 “ya-csv":"*” 然后:切换到目录中 npm install var csv = require(‘ya-csv’); var nation = req.files.nation.path; var reader = csv.createCsvFileReader(nation, { 'separator’: ',’, 'quote’: '"’, 'escape’: '"’, 'comment’: '’, 'columnsFromHeader’: 'true’, }); reader.addListener('data’, function(data) { if (data) { Nation.create(data, function(err, nation) { if (err) { res.json({ code: 'ERR’, msg: ‘err’ + err }); }; if (nation) { nation.save(); res.json({ code: 'OK’, msg: sprintf(‘success’) }); }; }) }; }); ==================另一种上传方式 fs.readFile(fname, function(err, data) { var data = gbk_to_utf8.convert(data); var str = data.toString(); var lines = str.split(‘\r\n’); var fields_name = []; fields_name = lines.shift().split(‘,’); var items = []; for (var i = 0; i < lines.length - 1; i++) { var row = {}; var fields = lines[i].split(‘,’); row.lng = fields.shift(); row.nation_code = fields.shift(); row.nation_name = fields.shift(); items.push(row); };
if (items) {
Nation.create(items, function(err, nation) {
if (err) {
res.json({
code: 'ERR',
msg: 'err' + err
});
};
if (nation) {
nation.save();
res.json({
code: 'OK',
msg: sprintf('success')
});
};
})
};
})