Next, we write the Node.js script, which is required to establish a database connection and execute the SQL snippet we just created.
The Node.js script: ./db/index.js
What happens here?
- Load the environment variables using
dotenv
- Read the SQL snippet
- Connect to the database (MySQL)
- Generate a random password (hashed)
- Execute the SQL snippet
At the end, the admin password is logged to the console if everything worked fine. Instead of using dotenv
you can also use fs.readFileSync
to load your database credentials from any other file.
If you’re not using MySQL you simply have to modify the database connection setup. I’m sure there’s an npm package for your database system that can handle this.
Last but not least let’s extend the package.json
scripts to simplify the execution of the Node script.
{
"scripts": {
// ...
"seed": "node db/index.js"
// ...
}
}
Now you can run the database seeding with a single command from the terminal: npm run seed
. That’s it! Your database is filled with dummy data and you can focus on the important stuff.
There’s also a GitHub repository available including an example application that makes use of database seeding. Have a look.