Saya membuat skrip impor NodeJS jika Anda menjalankan nodeJS dan data Anda dalam bentuk berikut (penawaran ganda + koma dan \ n baris baru)
INSERT INTO <your_table> VALUEs( **CSV LINE **)
Yang ini dikonfigurasi untuk berjalan di http: // localhost: 5000 / import .
Saya pergi baris demi baris dan membuat string kueri
"city","city_ascii","lat","lng","country","iso2","iso3","id"
"Tokyo","Tokyo","35.6850","139.7514","Japan","JP","JPN","1392685764",
...
server.js
const express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
app = express(),
port = process.env.PORT || 5000,
pj = require('./config/config.json'),
path = require('path');
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: false,
})
);
var Import = require('./routes/ImportRoutes.js');
app.use('/import', Import);
if (process.env.NODE_ENV === 'production') {
// set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.listen(port, function () {
console.log('Server is running on port: ' + port);
});
ImportRoutes.js
const express = require('express'),
cors = require('cors'),
fs = require('fs-extra'),
byline = require('byline'),
db = require('../database/db'),
importcsv = express.Router();
importcsv.use(cors());
importcsv.get('/csv', (req, res) => {
function processFile() {
return new Promise((resolve) => {
let first = true;
var sql, sqls;
var stream = byline(
fs.createReadStream('../PATH/TO/YOUR!!!csv', {
encoding: 'utf8',
})
);
stream
.on('data', function (line, err) {
if (line !== undefined) {
sql = 'INSERT INTO <your_table> VALUES (' + line.toString() + ');';
if (first) console.log(sql);
first = false;
db.sequelize.query(sql);
}
})
.on('finish', () => {
resolve(sqls);
});
});
}
async function startStream() {
console.log('started stream');
const sqls = await processFile();
res.end();
console.log('ALL DONE');
}
startStream();
});
module.exports = importcsv;
db.js adalah file konfigurasi
const Sequelize = require('sequelize');
const db = {};
const sequelize = new Sequelize(
config.global.db,
config.global.user,
config.global.password,
{
host: config.global.host,
dialect: 'mysql',
logging: console.log,
freezeTableName: true,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
}
);
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Penafian: Ini bukan solusi yang sempurna - Saya hanya mempostingnya untuk para dev yang berada di bawah timeline dan memiliki banyak data untuk diimpor dan menghadapi masalah konyol ini. Saya kehilangan banyak waktu dalam hal ini dan saya berharap untuk menyediakan dev lain pada waktu yang hilang.