简体   繁体   English

我如何使用 nodejs 在 mysql 数据库中保存 json 文件

[英]how can i save json file in mysql database using nodejs

I'm trying to import a JSON file and store it in the MySQL database but resources are not much clear and I don't know how I can fix what I need trying with this code which is a store CSV file and trying to convert it into JSON file: any help or idea or resourses to know how I can fix it or make it much better?我正在尝试导入 JSON 文件并将其存储在 MySQL 数据库中,但资源不是很清楚,我不知道如何修复我需要尝试使用此代码的存储 ZCC8D68C551C4A9A6D5313E07DE 文件进入 JSON 文件:任何帮助或想法或资源知道我如何修复它或让它变得更好?

const fs = require("fs");
const express = require('express')
const app = express()
const bodyparser = require('body-parser')
const csv = require('fast-csv');
const mysql = require('mysql')
const multer = require('multer')
const path = require('path')

fs.readFile("todo.json", (err, data) => {
  let todotxt = convertJSON2TXT(data); 
  saveTXT(todotxt); 
});

function convertJSON2TXT(data) {
  let todotxt = "";
  let todo = JSON.parse(data.toString());
  todo.forEach((val) => {
    val.isArchived = val.isArchived ? 1 : 0;
    val.startDate = val.startDate.replace("T", " ").substr(0, 19);
  });
  todo.forEach((val) => {
    todotxt += `${val.id}\t${val.todo}\t${val.isArchived}\t${val.startDate}\r\n`;
  });

  return todotxt.substr(0, todotxt.length - 2);
}

function saveTXT(todotxt) {
  fs.writeFile("todo.txt", todotxt, (err) => {
    if (err) {
      console.log("error occurs");
    } else {
      console.log("write to todo.txt:");
      console.log(todotxt);
    }
  });
}


//use express static folder
app.use(express.static("./public"))

// body-parser middleware use
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({
    extended: true
}))

// Database connection
const db = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "test"
})

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');
});

//@type   POST
// upload csv to database
app.post('/uploadfile', upload.single("uploadfile"), (req, res) =>{
    convertJSON2TXT(__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 todo (id, todo, isArchived, startDate) 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 || 3000
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`))

Doesn't data.toString() give you the JSON as a string ? data.toString()不是给你 JSON作为字符串吗? If so, there should be no need to "parse" it into an "object", then try to convert back to a "string".如果是这样,则无需将其“解析”为“对象”,然后尝试转换回“字符串”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Node.js进行多个API调用以将所有结果保存在一个json文件中? - How can I make multiple API calls to save all results in one json file using Nodejs? 如何在NodeJS中使用一个命令将数组保存到文件,并使用另一个命令将文件保存到数组? - How can I save an array to a file using one command, and save that file to an array using another command in NodeJS? 如何使用NodeJs流过滤JSon文件 - How can I filter JSon File using NodeJs streams AngularJS、NodeJS:将数据保存到 Json 文件或数据库 - AngularJS, NodeJS: save data to a Json file or a database 如何使用 NodeJS 中的 mysql 库将查询结果保存在变量中? - How can I save the query result in a variable using the mysql library in NodeJS? 我如何将 json 数据保存到数据库中并在保存后进行 foreach? - How i can save json data into database and to foreach after save? 如何使用mysql数据库中的nodejs和socket.io在网页上实时更新? - How can I get real time update on a webpage using nodejs and socket.io from a mysql database? 如何使用Nodejs后端将文件上传到MySQL数据库并显示照片 - How to upload a file to MySQL database using Nodejs backend and display the photo 如何使用nodejs将文本文件中的数据库转换为json数据 - how to convert database in text file to json data using nodejs 如何查看我保存到“MySQL”数据库中的结果? - How can I see the result of what I save into the "MySQL" database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM