To use this package, simply do the following:
-
Make sure the first row of your CSV file contains the column titles for your file.
-
Make sure these column titles in your CSV file match the field names of your MYSQL db table.
-
Run
npm i import-csv-mysql -
In your code, import this package, destructure & call the readCSVFile function
const { readCSVFile } = require('import-csv-mysql') -
Get the path of your CSV file. You can use the
pathnode core module to achieve this easily.const path = require('path') const root = path.parse(process.cwd()).root const fileToRead = path.join(root, 'path', 'to', 'your', 'file.csv') -
Provide valid values for the following keys:
const dbSettings = { host: 'xxxx', user: 'xxxx', password: 'xxx', dbName: 'xxx', tableName: 'xxx', passwordHashSalt: 'xxx', tableFields: ['pass', 'mysql', 'table', 'fieldnames', 'that', 'match', 'with', 'csv', 'column', 'titles'] }If you don't have a password column in your CSV file to pass password values to dbTable, ignore the
passwordHashSaltkey-value pair.If you do have a password column in your CSV file to pass password values, include the
passwordHashSaltkey-value pair and pass the password salt which you'll like to use to hash the passwords in your file, before inserting into db.Do not pass an empty value to
passwordHashSalt; if you don't have a password hashing salt, please omit thepasswordHashSaltkey-value pair entirely or passnullas the value.The value of tableFields must be an array of strings e.g.
['first_name', 'last_name', 'email_address'] -
Pass the
fileToReadanddbSettingsvariables as arguments to thereadCSVFilefunctionreadCSVFile(fileToRead, dbSettings) -
Run your code.
-
If you followed these instructions, the records in your CSV file should now be imported into the mysql dbTable provided in
dbSettings.