使用 nodejs 将 CSV 文件导入 mysql 数据库

import CSV file into mysql database using nodejs

我正在尝试使用 nodejs 将 CSV 文件上传到 MySQL 数据库...它运行成功并添加了行,但它给了我一个错误。 这是我的代码:

//use express static folder
app.use(express.static("./public"))
 
// body-parser middleware use
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))
 
 
db.connect(function (err) {
    if (err) {
        return console.error('error: ' + err.message);
    }
    console.log('Connected to the MySQL server.');
})
 
//! Use of Multer
var storage = multer.diskStorage({
    destination: (req, file, callBack) => {
        callBack(null, './uploads/')    
    },
    filename: (req, file, callBack) => {
        callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})
 
var upload = multer({
    storage: storage
});
 
//! Routes start
 
//route for Home page
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
 
// upload csv to database
app.post('/uploadfile', upload.single("uploadfile"), (req, res) =>{
    UploadCsvDataToMySQL(__dirname + '/uploads/' + req.file.filename);
    console.log('CSV file data has been uploaded in mysql database ' + err);
});
 
function UploadCsvDataToMySQL(filePath){
    let stream = fs.createReadStream(filePath);
    let csvData = [];
    let csvStream = csv
        .parse()
        .on("data", function (data) {
            csvData.push(data);
        })
        .on("end", function () {
            // Remove Header ROW
            csvData.shift();
  
            // Open the MySQL connection
            db.connect((error) => {
                if (error) {
                    console.error(error);
                } else {
                    let query = 'INSERT INTO files (File_ID, File_Name) VALUES ?';
                    db.query(query, [csvData], (error, response) => {
                        console.log(error || response);
                    });
                }
            });
             
            // delete file after saving to MySQL database
            // -> you can comment the statement to see the uploaded CSV file.
            fs.unlinkSync(filePath)
        });
  
    stream.pipe(csvStream);
}
 
//create connection
const PORT = process.env.PORT || 8000
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`))

这是文件上传后 PowerShell 中出现的错误:

ReferenceError:错误未定义 在 C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\index.js:79:72 在 Layer.handle [作为 handle_request] (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\express\lib\router\layer.js:95:5) 接下来 (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\express\lib\router\route.js:137:13) 在阵列。 (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\multer\lib\make-middleware.js:53:37) 在听众处(C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\on-finished\index.js:169:15) 在 onFinish (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\on-finished\index.js:100:5) 在回调 (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\ee-first\index.js:55:10) 在 IncomingMessage.onevent(C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\ee-first\index.js:93:5) 在 IncomingMessage.emit(节点:事件:341:22) 在 endReadableNT(节点:internal/streams/readable:1294:12) 结果集标题 { 字段数:0, 受影响的行数:3, insertId: 33333, 信息:'Records: 3 Duplicates: 0 Warnings: 0', 服务器状态:2, 警告状态:0 }

在以下区域中,您在控制台日志中添加了 err,该文件未在文件中定义

// upload csv to database
app.post('/uploadfile', upload.single("uploadfile"), (req, res) =>{
   UploadCsvDataToMySQL(__dirname + '/uploads/' + req.file.filename);
   console.log('CSV file data has been uploaded in mysql database ' + err); //<----- here err is not defined 
});

只需删除它并尝试问题是否已解决