$99 Websites + Website Design 5505 Sun Harbor Road Panama City, Florida 32401 850-329-3425 http://website99.us https://www.google.com/maps/place/$99+Websites+%2B+Website+Design/@30.1842909,-85.7322502,15z/data=!4m5!3m4!1s0x0:0x61b35c1bb4fa6eac!8m2!3d30.1842909!4d-85.7322502
Friday, August 31, 2018
My Mom Quit Her Job After 9 Years And It Taught Me How to Value a Talented Employee
1 Surprising Sign in a Job Interview the Hiring Manager's a Narcissist
The #1 Mistake Companies Make When Promoting People Into Management
The 1 Retention Tool Companies Don't Utilize Enough
4 Telltale Signs That Your Workplace Is Toxic
Labor Day Lessons From Business Celebrities
Working Too Hard Could Be Harmful to Your Career, Says a New Survey of 52,000 Employees
Elon Musk is the Master of Taking Action Quickly -- Why That Might Not Be the Best for a Leader
3 Tactics to Build Better Relationships with Strangers
How Focusing on 'Strength-Based Development' Can Boost Your Profits by Nearly 30 Percent
A 4-Word Master Class in Leadership From Steve Jobs
How to Tell the Difference Between Real Trends and Fads on Social Media
The 1 Thing the Founder of KIND Says You Need to Be Successful
Forget Winning the Battle Against Fake News and Fake Influence. Instead, Try This
Ask Yourself These 3 Simple Questions to Eliminate Toxic Relationships From Your Life
4 Easy Steps To Develop Game Changing Bravery
How This New York Brewery Found a Golden Product Opportunity With 'Game of Thrones'
3 Things You Can Learn From the Office Jerk
How to Let Go Of An Outdated Requirement And Hire The Best
Proof That LEGO Knows Exactly How to Inspire Its Fans? Behold This 1 Million-Piece Drivable Sports Car
Why Forgetting Something Actually Helps You Learn, According to a Cognitive Psychologist
3 Things Hard-Working Entrepreneurs Must Do Before Leaving for Vacation
Ellen Pao: This Is a Critical Moment for Women in Silicon Valley
7 Lessons I Learned From Interviewing Some of the World's Most Successful Leaders
The Ingenious Way This New York Butcher Sells 3,000 Pounds of Meat a Week
Find It Hard to Get Your Team to Do Things the Way You Want? Here's What You Can Do About It
Why Uber Could Lose the Race to the First Ridesharing IPO
Smart Ways to Manage These 6 Common Business Travel Challenges
Want to Catapult Your Company Forward? Try Listening to Your People
3 Core Principles You Need to Attract and Retain Top Talent
3 Lessons Every Entrepreneur Can Learn from Aretha Franklin, John McCain and Neil Simon
Teachers Who Buy Their Own Supplies Are About to Pay More
Why You Should Encourage Your Employees to Think Like Entrepreneurs
An Open Letter to Young People on How to Succeed (From an Aging CEO)
Inclusive Innovation Results in 5.5 Times More Revenue Growth
5 Ways To Practice Self-Care, Even as a CEO
Pressure Is a Privilege: Why You Should Always Seize the Opportunities That Scare You Most
Is Believing in Your Business Idea Enough? Not Unless You Add This.
3 Daily Habits Successful Entrepreneurs Practice to Stay at the Top of Their Game
3 Good Reasons to Stop Worrying So Much About Your Kids, According to Experts
This Best-Selling Author's Secret to Maximum Productivity
Are Your Managers Feeling Overwhelmed and Underappreciated? Here's How to Set Them Up For Success
How to Refocus Your Personal Brand With Video
This 30-Minute Workout Builds Muscle and Burns Fat in Less Than Half the Time of a Normal Workout
20 Ways To Improve Your Emails Today
Do Your Tattoos Mean You Won't Get Hired? Studies Say Yes (Unless This Happens)
Are You Cut Out to Be a Mentor? These 6 Questions Will Help You Find Out
If You Haven't Hired Women You May be Missing Some of the Best Talent, According to Walmart.com CEO
No Marketing Budget? Here Are 4 Creative Ways to Land New Customers
The Subtle Discrimination Parents Face at Work--and 1 CEO's Effective Solution
Ivy League Universities Are Seeing Crazy High Enrollment in Courses on This Surprising Subject
5 Red Flags of Small Business Fraud--and What You Can Do to Snuff it Out
Two Grown Men Got Into a Fight On a Plane. A 13-Year-Old Girl Gave Them Sage Advice
Forget Company Culture -- Managers Should Focus On This
KIND's Daniel Lubetzky on Getting His Start, His Legacy, and Knowing When to Step Back
10 Workplace Behaviors You'll Regret (and How to Avoid Them)
7 Reasons Getting Your Employees to Vote Will Help Your Business
Middle Class and Struggling Financially? Math Says You Shouldn't Blame Yourself
4 Ways You Can Feel Successful Now Even if You're Failing
How Celebrity Kids Made This Startup's Product the Biggest Hit of the Summer
Are You to Blame for Your Company's Toxic Culture? Here's How to Fix It
How This Mother of 5 Turned Scrap Leather Into One of the Fastest-Growing Companies in America
Meet the Woman Behind a $2 Million Superfood Business Helping Women Farmers in Africa
Why Do Women Entrepreneurs Pay Themselves 28 Percent Less Than Men?
Please Quit Saying Serena Williams Is a Great Tennis Player (She's an Icon)
Thursday, August 30, 2018
This One Simple Rule Can Save You Pain in Your Next Venture
Good Design Is Crucial to Business Success. Here's Why
Use These Secrets to Sell More on Amazon, Faster
How to Supercharge Your Team's Development for the Long-Term
What 'Love Language' Does Your Employee Speak?
5 Things Good 'People' Managers Have In Common
How to Free Up Your Time to Focus on Building Your Business
How to to Recover Your Business From a Natural Disaster
3 Steps to Help Lower Your Post-Vacation Anxiety
WhatsApp Has a New Feature That Will Charge Businesses if They Don't Respond in 24 Hours -- And It's Genius
The Guys Who Designed YouTube Just Re-Designed the Coffee Break
If Quitting a Job Is Just Too Stressful, This Service Will Do It for a Fee
Avoid These 3 Pitfalls During High-Stakes Conversations
There's Only One Real Measurement for Great Leadership. Do You Have it?
Know Someone Who Needs Help at Work? Try These 3 Approaches to Offer Your Support
19 Job Perks Millennials Have That Baby-Boomer's Didn't
5 Early Warning Signs It Might Be Time to Quit Your Job
Logistics Is Incredibly Complicated. This Company Is Making It Simple--With Some Help From Emojis
According to an MIT Study, This Is the Best Time in Life to Start a Business
4 Tips to Help You Nail Your Next Startup Interview
In-N-Out Has a Big New Problem That Could Seriously Threaten Its Business (Or Could It?)
This Viral Chick-fil-A Video Points Out 2 Vital Things the Company Offers Its Employees
How This Musician and Others Continue to Take a Stand for Unjust Rules
How to Get Your Product in a Major Retail Store
Looking to Close the Deal? Avoid These 5 Presentation Pitfalls
5 Questions You Need to Ask Your Best Employees If You Want Them to Stay
Aisha Tyler's Perfect Comedy Rule Applies to Your Business, Too
Should You Work at a Startup or an Established Company? Ask These 3 Questions to Decide
Checking Work Email After Hours Is Harmful to Employee Health, According to New Research
How Mentors Can Close the Tech Diversity Gap
Amazon Fights Back Against Bernie Sanders's Claims About Low Wages and Poor Working Conditions
Why Getting Face Time with Your Source is a Brand Accelerator
5 Questions You Should Ask Immediately After a Failure
3 Questions You Must Ask During Your Next Job Interview
The One Question You Should Ask That Will Make You A Better Leader
Van Jones on How to Find Talent and Open Opportunities
3 Foolproof Ways to Make Your Remote Team More Productive
1 Thing Netflix Did Successfully That Took It From Commodity to Category Leader
Most Companies Treat This Detail as an Afterthought Even Though It Has a Big Impact on the Customer Experience
8 Tips for Effective Leadership
3 Keys to Deliver An Amazing Presentation Suited to the Room
Your Worst Hire Might Be the Secret to Building Your Best Culture
What's the Future of Software as a Service? The Answer May Surprise You.
4 Steps to Launch a Lead Broker Business
How to Network With Important People, According to a Harvard-Educated Startup Founder
Why 'Early to Bed, Early to Rise' Is a Myth (and Night Owls Can Finally Rejoice)
How Culturally Aware are You?
Serena Williams Just Played in a Tutu--Twice--and Teaches an Incredible Lesson that Actions are More Powerful than Words
The Inspiring Reason Why This Entrepreneur Gave Up His Role as CEO
Why Paying Attention to This Overlooked Office Feature Might Have a Huge Productivity Payoff
33 Quotes That Will Inspire You to Increase Your Emotional Intelligence
3 Things Nobody Tells You About the Stress of Selling a Business
6 High-Tech Apparel Products to Give You a Confidence Boost at Every Job Interview
How to Nurture Your Kids' Creativity--and Future-Proof Their Skills
9 Ways to Get Rid of Anxiety in 5 Minutes or Less
Traditional Thinking Is Holding You Back as a Leader. Here's How to Change Your Perspective
What 1 Sentence in John McCain's Final Statement Should Teach You About Leaving a Legacy
Elon Musk's Recent Nervous Breakdown is a Warning Sign to Business Owners Everywhere
This 32-Minute Morning Routine Is the Best Way to Start Your Day, According to Science
5 TED Talks That Will Make You Feel More Powerful
How This Toy Startup Spent $4 Million to Save Its Holiday Sales When Everything (Literally) Fell Apart
The Big Lie Facebook and Twitter Tell Themselves (And Us)
American Airlines Flight Attendants Will Picket Their Own Airline Today Over Its 'Inhumane' and 'Punitive' New Policy
Delta Air Lines Flight Stopped by Guy Doing Push Ups on the Runway (That's When Things Got Really Weird)
She Started a Gym for Your Face, Thanks to Ayahuasca and a Helpful Shaman
When's the Best Time to Book Your Flight for Thanksgiving? It's a Lot Sooner Than You Think
3 Unexpected Office Tweaks for Happier and More Productive Employees
This Founder Had to Completely Start Over at 40. She Responded By Building One of the Fastest-Growing Companies in America
Want to Raise Successful Daughters? You May Be Making This Mistake Without Knowing It
Twitter's CEO Asked Elon Musk to Speak to All of Twitter's Employees. Here's the Truly Surprising Way It Changed 1 Musk Fan's Life
3 Changes America Needs to Make to Revive Our Entrepreneurial Spirit
3 Business Clichés You Should Actually Embrace
No Airline Pilot Has Ever Done This Before and No Pilot Will Likely Do It Again (Let's Hope)
Wednesday, August 29, 2018
Learning from Paul Manafort's Crimes Can Save You $100,000. Here's How
How Not to Panic and Other Leadership Tips From the Astronaut Who Survived a Seriously Scary Space Walk
These 3 Job Interview Tips Are So Easy (and Successful) That They Feel Like Cheating
How to Decide Between Etsy, Amazon, and Shopify for Selling Online
The 3 Times Criticizing a Competitor Can Actually Help Your Startup
How An 18-Year-Old Kid Turned The Death Of His Father Into A Positive Experience
3 Sure Signs Your Company's Branding Is Outdated (Plus, How to Fix It)
What a New NAFTA Means for You
Steve Job's Alternative to the Open Plan Office
How to Get the Green Light for Your Next Business Trip
4 Lifestyle Habits That Will Make You Successful
Teenage Entrepreneurs Are Your New Start-Up Competition
How Your Tone of Voice Can Make People Appreciate Your Feedback (Instead of Thinking You're a Jerk)
Why Didn't Prince or Aretha Franklin Leave a Will?
Trump Accuses Google, Facebook and Twitter of Biased Search Results
Top 10 Marketing Conferences for Fall 2018
Instagram Wants You to Apply for a Verified Account. Here's Why
Here's How Google Search Works, Mr. President
Think Instagram is Your Best Marketing Tool Because of Its Popularity? Think Again
Leaders Can Burn Out Really Easily. Here Are Five Steps to Fix It
1 Way Mark Cuban Uses Personal Branding to Redefine What It Means to Be Rich
How To Handle Personal Criticism Just Like Serena Williams Did
How Every Entrepreneur Should Use Technology to Build Stronger Relationships
Need Money? Here's Why SBA Loans Are Great Resources--Even If You Don't Think You Qualify
3 Essential Questions to Ask Before Hiring a PR Agency to Help You Attract Media Attention
How to Use the Symfony Filesystem Component
In this article, we're going to explore the Symfony Filesystem component, which provides useful methods to interact with a file system. After installation and configuration, we'll create a few real-world examples of how to use it.
The Symfony Filesystem Component
More often than not, you'll need to interact with a file system if you're dealing with PHP applications. In most cases, you either end up using the core PHP functions or create your own custom wrapper class to achieve the desired functionality. Either way, it's difficult to maintain over a longer period of time. So what you need is a library which is well maintained and easy to use. That's where the Symfony Filesystem component comes in.
The Symfony Filesystem component provides useful wrapper methods that make the file system interaction a breeze and a fun experience. Let's quickly look at what it's capable of:
- creating a directory
- creating a file
- editing file contents
- changing the owner and group of a file or directory
- creating a symlink
- copying a file or directory
- removing a file or directory
- and more
In this article, I'll show you how to unleash the power of the Symfony Filesystem component. As usual, we'll start with installation and configuration instructions, and then we'll implement a few real-world examples to demonstrate the key concepts.
Installation and Configuration
In this section, we're going to install the Symfony Filesystem component. I assume that you've already installed Composer in your system as we'll need it to install the Filesystem component available at Packagist.
So go ahead and install the Filesystem component using the following command.
$composer require symfony/filesystem
That should have created a composer.json file, which should look like this:
{ "require": { "symfony/filesystem": "^4.1" } }
So that's the installation part, but how are you supposed to use it? In fact, it's just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.
<?php require_once './vendor/autoload.php'; // application code ?>
A Real-World Example
In this section, we'll create an example which demonstrates how you could use the Filesystem component in your applications to perform various filesystem operations.
To start with, let's go ahead and create the index.php file with the following contents.
<?php require_once './vendor/autoload.php'; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Exception\IOExceptionInterface; // init file system $fsObject = new Filesystem(); $current_dir_path = getcwd(); // make a new directory // create a new file and add contents // copy a directory // remove a directory
Here, we've initialized the Filesystem
object to $fsObject
and saved the current directory to $current_dir_path
. In the upcoming sections, we'll use $fsObject
to perform different operations.
Make a New Directory
First, we'll create a new directory.
//make a new directory try { $new_dir_path = $current_dir_path . "/foo"; if (!$fsObject->exists($new_dir_path)) { $old = umask(0); $fsObject->mkdir($new_dir_path, 0775); $fsObject->chown($new_dir_path, "www-data"); $fsObject->chgrp($new_dir_path, "www-data"); umask($old); } } catch (IOExceptionInterface $exception) { echo "Error creating directory at". $exception->getPath(); }
Here, we've used the exists
method to check if the foo directory already exists before creating it.
Next, we used the mkdir
method to create the foo directory with the 0775 permissions, which means readable and executable by all, but only writable by the file owner and their group. (This is the octal notation for filesystem permissions—to learn more, check out this breakdown of octal notation.) Further, we've used the chown and chgrp methods to change the owner and group of the foo directory.
Create a New File and Add Contents
In this section, we'll create a new file and add contents to that file.
// create a new file and add contents try { $new_file_path = $current_dir_path . "/foo/bar.txt"; if (!$fsObject->exists($new_file_path)) { $fsObject->touch($new_file_path); $fsObject->chmod($new_file_path, 0777); $fsObject->dumpFile($new_file_path, "Adding dummy content to bar.txt file.\n"); $fsObject->appendToFile($new_file_path, "This should be added to the end of the file.\n"); } } catch (IOExceptionInterface $exception) { echo "Error creating file at". $exception->getPath(); }
Here, we've used the touch
method to create a new file and then used chmod
to set its permissions to 0777—globally readable, writable, and executable.
Once the file is created, you can use the dumpFile
method to add contents in that file. On the other hand, if you want to add contents to the already existing file, you can use the appendToFile
method, as shown in the above example.
Copy a Directory
So far, we've created the foo directory and the bar.txt file using the $fsObject
object. In this section, we'll see how to copy a directory along with the contents.
//copy a directory try { $src_dir_path = $current_dir_path . "/foo"; $dest_dir_path = $current_dir_path . "/foo_copy"; if (!$fsObject->exists($dest_dir_path)) { $fsObject->mirror($src_dir_path, $dest_dir_path); } } catch (IOExceptionInterface $exception) { echo "Error copying directory at". $exception->getPath(); }
As you can see, first we built the path names with string concatenation. Then, once we made sure the directory didn't already exist using the exists
method, we used the mirror
method to copy the foo directory into the foo_copy directory.
Remove a Directory
Finally, let's see how to remove a directory.
//remove a directory try { $arr_dirs = array( $current_dir_path . "/foo", $current_dir_path . "/foo_copy" ); $fsObject->remove($arr_dirs); } catch (IOExceptionInterface $exception) { echo "Error deleting directory at". $exception->getPath(); }
Again, it's pretty straightforward—to delete a directory, you just use the remove
method.
You can find the complete code to index.php in our GitHub repo.
Conclusion
So that's a brief introduction to the Symfony Filesystem component. The Symfony Filesystem component provides methods that make interaction with a file system a breeze. We looked at how to install the component, and we created a handful of examples to demonstrate various aspects of the component.
I hope that you've enjoyed this article, and feel free to post your thoughts using the feed below!
How to Get Your Employees to Respect You by Respecting Them
Companies Are Selling Vapable Vitamins. Don't Inhale the Hype
17 Ways to Be More Productive This Fall
6 Tools Your Business Should Try This Fall
This Shark Tank Startup Wants to Help You Crush the GMAT and Get Into a Top B-School
Want to Build a Great Culture? Start By Leaving Your Ego at the Door
Do You Do This Simple Thing Jeff Bezos Associates With the Smartest People? (You Probably Do, But Not Enough)
The Best Industries for Flexible Jobs
3 Lessons Millennial Entrepreneurs can Learn from Big Business Failures
Need To Move Your Marketing Up a Notch? Try Hiring a Fractional CMO
Don't Make These Two Common New Leader Mistakes When Trying To Build Your Credibility
I Set out to Uncover Who Ran the "Fake Warren Buffett" Twitter Account. Here's What I Learned
Are You Using Slack Correctly? Try These These 4 Tips to Remove Distractions and Be More Productive
We Tested the Best Beef Jerky on the 2018 Inc. 5000 (Because There Was A Lot)
The Notion of Work-Life Balance Is Unrealistic. Here's a Better Way to See It
17 Amazing Quotes from Equally Amazing Women
Need More Space in Your Home? A Former Apple and Tesla Engineer Invented a Clever Solution
Overwhelmed by Stress? These 5 Things Will Help Find a More Productive Head Space
5 Questions That Will Challenge Your Team to Think Beyond the Short Term
1 Simple Way to Instantly Improve Your Leadership That Most Bosses Are Probably Overlooking
This Major League Pitching Coach Found the Secret to Productivity. It Works for Any Entrepreneur
OK, Open Plan Offices Kill Collaboration But at Least They Won't Kill You From Sitting All Day
Wegmans, Virgin and Southwest Airlines Know the Secret to a Winning Culture
7 Surefire Tips To Ace Your Next Q&A
NBA Star Steph Curry Writes Impassioned Essay: I want My Daughters to Have Equal Pay
How a Harvard-Trained Lawyer Built a $2.2 Million Company on Hand-Painted Chocolates
These Are the 7 Fastest-Growing Companies in New Orleans This Year
It's Time To Call BS On Waking Up Early, Night Owls Rejoice: Here's Why
Why Creating an Investor's Deck Should Be One of Your First Steps as an Entrepreneur
United Airlines President Says If Families Want to Sit Together, They Should Pay Extra
This 1 Verizon Customer Support Mistake Impacted Thousands of People and It Could Have Been Prevented
Tuesday, August 28, 2018
When Over Half of Communication Comes Through Body Language, Do You Understand How You Interact With Others When You're Not in the Room?
This Labor Day Give the Gift of Prioritizing Employee Feedback
NBA Champion Magic Johnson's Brilliantly Practical Mindset for Success in Business
What Every Entrepreneur Can Learn From the 5 Most Successful Tech Companies Ever
How Amazon, Netflix, and Facebook Avoided Falling into the Trend Trap
The Brilliant Way the Last Blockbuster Video in America is Staying Relevant
How to Handle the 4 Most Common Meeting Saboteurs
Inc. Uncensored: Why Boutique Fitness Is Winning the Category
Finding and Solving an Important Customer Pain
A Passenger Catches an Airport Worker Doing Something Unconscionable (Did It Delay the Flight?)
The Simple, 11-Word Formula to Becoming a Thought Leader
Why You May Be More Powerful Than Taylor Swift
The 3 Simple Questions Jeff Bezos Asks Himself Before Making a Hiring Decision
Are You Traveling for Work More Often Than Not? Don't Let It Knock You Off Balance
Why Every Small Business Owner Needs to Start Their Succession Planning Now
35 Powerful Pieces of Advice to Give You a Lift When Your Self-Esteem Takes a Hit
How This Schoolteacher Beat 30,000 People to Become the World Champion of Public Speaking
The Scathing New Book by the Daughter of Steve Jobs Teaches Us the Value of Relationships
From Pet Supplies to Pre-Packaged Beverages: Interview with Lemonkind Founder and CEO, Irene Rojas Stanbury
7 Signs It's Time to Expand Your Team
Laugh to Win in Business and Life: The Surprising Benefits of Comedy
How to Cure Your Employees' Fear, Doubt and Procrastination
7 Ways Entrepreneurs Can Take Advantage of the Booming Economy in 2018
Forget Past Experience. These Are the 4 Superior Traits to Look for in Your Next Hire
In 1 Simple Sentence, Warren Buffet Explains the Power of Personal Branding
5 Annoying Buzz Phrases Entrepreneurs Need to Stop Using
How Poor Cybersecurity and One Bad Hire Could Cost Your Company Millions
Code Your First API With Node.js and Express: Connect a Database
Build a REST API With Node.js and Express: Connecting a Database
In the first tutorial, Understanding RESTful APIs, we learned what the REST architecture is, what HTTP request methods and responses are, and how to understand a RESTful API endpoint. In the second tutorial, How to Set Up an Express API Server, we learned how to build servers with both Node's built-in http
module and the Express framework, and how to route the app we created to different URL endpoints.
Currently, we're using static data to display user information in the form of a JSON feed when the API endpoint is hit with a GET
request. In this tutorial, we're going to set up a MySQL database to store all the data, connect to the database from our Node.js app, and allow the API to use the GET
, POST
, PUT
, and DELETE
methods to create a complete API.
Installation
Up to this point, we have not used a database to store or manipulate any data, so we're going to set one up. This tutorial will be using MySQL, and if you already have MySQL installed on your computer, you'll be ready to go on to the next step.
If you don't have MySQL installed, you can download MAMP for macOS and Windows, which provides a free, local server environment and database. Once you have this downloaded, open the program and click Start Servers to start MySQL.
In addition to setting up MySQL itself, we'll want GUI software to view the database and tables. For Mac, download SequelPro, and for Windows download SQLyog. Once you have MySQL downloaded and running, you can use SequelPro or SQLyog to connect to localhost
with the username root
and password root
on port 3306
.
Once everything is set up here, we can move on to setting up the database for our API.
Setting Up the Database
In your database viewing software, add a new database and call it api
. Make sure MySQL is running, or you won't be able to connect to localhost
.
When you have the api
database created, move into it and run the following query to create a new table.
CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(30) DEFAULT '', `email` varchar(50) DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This SQL query will create the structure of our users
table. Each user will have an auto-incrementing id, a name, and an email address.
We can also fill the database with the same data that we're currently displaying through a static JSON array by running an INSERT
query.
INSERT INTO users (name, email) VALUES ('Richard Hendricks', 'richard@piedpiper.com'), ('Bertram Gilfoyle', 'gilfoyle@piedpiper.com');
There is no need to input the id
field, as it is auto-incrementing. At this point, we have the structure of our table as well as some sample data to work with.
Connecting to MySQL
Back in our app, we have to connect to MySQL from Node.js to begin working with the data. Earlier, we installed the mysql
npm module, and now we're going to use it.
Create a new directory called data and make a config.js file.
We'll begin by requiring the mysql
module in data/config.js.
const mysql = require('mysql');
Let's create a config
object that contains the host, user, password, and database. This should refer to the api
database we made and use the default localhost settings.
// Set database connection credentials const config = { host: 'localhost', user: 'root', password: 'root', database: 'api', };
For efficiency, we're going to create a MySQL pool, which allows us to use multiple connections at once instead of having to manually open and close multiple connections.
// Create a MySQL pool const pool = mysql.createPool(config);
Finally, we'll export the MySQL pool so the app can use it.
// Export the pool module.exports = pool;
You can see the completed database configuration file in our GitHub repo.
Now that we're connecting to MySQL and our settings are complete, we can move on to interacting with the database from the API.
Getting API Data From MySQL
Currently, our routes.js
file is manually creating a JSON array of users, which looks like this.
const users = [{ ...
Since we're no longer going to be using static data, we can delete that entire array and replace it with a link to our MySQL pool.
// Load the MySQL pool connection const pool = require('../data/config');
Previously, the GET
for the /users
path was sending the static users
data. Our updated code is going to query the database for that data instead. We're going to use a SQL query to SELECT
all from the users
table, which looks like this.
SELECT * FROM users
Here is what our new /users
get route will look like, using the pool.query()
method.
// Display all users app.get('/users', (request, response) => { pool.query('SELECT * FROM users', (error, result) => { if (error) throw error; response.send(result); }); });
Here, we're running the SELECT
query and then sending the result as JSON to the client via the /users
endpoint. If you restart the server and navigate to the /users
page, you'll see the same data as before, but now it's dynamic.
Using URL Parameters
So far, our endpoints have been static paths—either the /
root or /users
—but what about when we want to see data only about a specific user? We'll need to use a variable endpoint.
For our users, we might want to retrieve information about each individual user based on their unique id. To do that, we would use a colon (:
) to denote that it's a route parameter.
// Display a single user by ID app.get('/users/:id', (request, response) => { ... }); });
We can retrieve the parameter for this path with the request.params
property. Since ours is named id
, that will be how we refer to it.
const id = request.params.id;
Now we'll add a WHERE
clause to our SELECT
statement to only get results that have the specified id
.
We'll use ?
as a placeholder to avoid SQL injection and pass the id through as a parameter, instead of building a concatenated string, which would be less secure.
pool.query('SELECT * FROM users WHERE id = ?', id, (error, result) => { if (error) throw error; response.send(result); });
The full code for our individual user resource now looks like this:
// Display a single user by ID app.get('/users/:id', (request, response) => { const id = request.params.id; pool.query('SELECT * FROM users WHERE id = ?', id, (error, result) => { if (error) throw error; response.send(result); }); });
Now you can restart the server and navigate to http://localhost/users/2
to see only the information for Gilfoyle. If you get an error like Cannot GET /users/2
, it means you need to restart the server.
Going to this URL should return a single result.
[{ id: 2, name: "Bertram Gilfoyle", email: "gilfoyle@piedpiper.com" }]
If that's what you see, congratulations: you've successfully set up a dynamic route parameter!
Sending a POST Request
So far, everything we've been doing has used GET
requests. These requests are safe, meaning they do not alter the state of the server. We've simply been viewing JSON data.
Now we're going to begin to make the API truly dynamic by using a POST
request to add new data.
I mentioned earlier in the Understanding REST article that we don't use verbs like add
or delete
in the URL for performing actions. In order to add a new user to the database, we'll POST
to the same URL we view them from, but just set up a separate route for it.
// Add a new user app.post('/users', (request, response) => { ... });
Note that we're using app.post()
instead of app.get()
now.
Since we're creating instead of reading, we'll use an INSERT
query here, much like we did at the initialization of the database. We'll send the entire request.body
through to the SQL query.
pool.query('INSERT INTO users SET ?', request.body, (error, result) => { if (error) throw error;
We're also going to specify the status of the response as 201
, which stands for Created
. In order to get the id of the last inserted item, we'll use the insertId
property.
response.status(201).send(`User added with ID: ${result.insertId}`);
Our entire POST
receive code will look like this.
// Add a new user app.post('/users', (request, response) => { pool.query('INSERT INTO users SET ?', request.body, (error, result) => { if (error) throw error; response.status(201).send(`User added with ID: ${result.insertId}`); }); });
Now we can send a POST
request through. Most of the time when you send a POST
request, you're doing it through a web form. We'll learn how to set that up by the end of this article, but the fastest and easiest way to send a test POST
is with cURL, using the -d (--data)
flag.
We'll run curl -d
, followed by a query string containing all the key/value pairs and the request endpoint.
curl -d "name=Dinesh Chugtai&email=dinesh@piedpiper.com" http://localhost:3002/users
Once you send this request through, you should get a response from the server.
User added with ID: 3
If you navigate to http://localhost/users
, you'll see the latest entry added to the list.
Sending a PUT Request
POST
is useful for adding a new user, but we'll want to use PUT
to modify an existing user. PUT
is idempotent, meaning you can send the same request through multiple times and only one action will be performed. This is different than POST
, because if we sent our new user request through more than once, it would keep creating new users.
For our API, we're going to set up PUT
to be able to handle editing a single user, so we're going to use the :id
route parameter this time.
Let's create an UPDATE
query and make sure it only applies to the requested id with the WHERE
clause. We're using two ?
placeholders, and the values we pass will go in sequential order.
// Update an existing user app.put('/users/:id', (request, response) => { const id = request.params.id; pool.query('UPDATE users SET ? WHERE id = ?', [request.body, id], (error, result) => { if (error) throw error; response.send('User updated successfully.'); }); });
For our test, we'll edit user 2
and update the email address from gilfoyle@piedpiper.com to bertram@piedpiper.com. We can use cURL again, with the [-X (--request)]
flag, to explicitly specify that we're sending a PUT request through.
curl -X PUT -d "name=Bertram Gilfoyle" -d "email=bertram@piedpiper.com" http://localhost:3002/users/2
Make sure to restart the server before sending the request, or else you'll get the Cannot PUT /users/2
error.
You should see this:
User updated successfully.
The user data with id 2
should now be updated.
Sending a DELETE Request
Our last task to complete the CRUD functionality of the API is to make an option for deleting a user from the database. This request will use the DELETE
SQL query with WHERE
, and it will delete an individual user specified by a route parameter.
// Delete a user app.delete('/users/:id', (request, response) => { const id = request.params.id; pool.query('DELETE FROM users WHERE id = ?', id, (error, result) => { if (error) throw error; response.send('User deleted.'); }); });
We can use -X
again with cURL to send the delete through. Let's delete the latest user we created.
curl -X DELETE http://localhost:3002/users/3
You'll see the success message.
User deleted.
Navigate to http://localhost:3002
, and you'll see that there are only two users now.
Congratulations! At this point, the API is complete. Visit the GitHub repo to see the complete code for routes.js.
Sending Requests Through the request
Module
At the beginning of this article, we installed four dependencies, and one of them was the request
module. Instead of using cURL requests, you could make a new file with all the data and send it through. I'll create a file called post.js that will create a new user via POST
.
const request = require('request'); const json = { "name": "Dinesh Chugtai", "email": "dinesh@piedpiper.com", }; request.post({ url: 'http://localhost:3002/users', body: json, json: true, }, function (error, response, body) { console.log(body); });
We can call this using node post.js
in a new terminal window while the server is running, and it will have the same effect as using cURL. If something is not working with cURL, the request
module is useful as we can view the error, response, and body.
Sending Requests Through a Web Form
Usually, POST
and other HTTP methods that alter the state of the server are sent using HTML forms. In this very simple example, we can create an index.html file anywhere, and make a field for a name and email address. The form's action will point to the resource, in this case http//localhost:3002/users
, and we'll specify the method as post
.
Create index.html and add the following code to it:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Node.js Express REST API</title> </head> <body> <form action="http://localhost:3002/users" method="post"> <label for="name">Name</label> <input type="text" name="name"> <label for="email">Email</label> <input type="email" name="email"> <input type="submit"> </form> </body> </html>
Open this static HTML file in your browser, fill it out, and send it while the server is running in the terminal. You should see the response of User added with ID: 4
, and you should be able to view the new list of users.
Conclusion
In this tutorial, we learned how to hook up an Express server to a MySQL database and set up routes that correspond to the GET
, POST
, PUT
, and DELETE
methods for paths and dynamic route parameters. We also learned how to send HTTP requests to an API server using cURL, the Node.js request
module, and HTML forms.
At this point, you should have a very good understanding of how RESTful APIs work, and you can now create your own full-fledged API in Node.js with Express and MySQL!
National Geographic Sent a Big Message with a Big Apology
Need an Entrepreneurial Boost? The Top 7 Podcasts for Inspiration in Business and Life
Want Your Team to Be More Creative? Turn On the Music
Why Southwest Has Been Profitable 45 Years in a Row
I Landed 2 Consecutive Companies on the Inc. 500 List--Without Any Funding. Here's How
Why Cleaning House Can Create a Bigger Mess
Want to Be a Better Communicator? Eliminate These Two Words From Your Vocabulary
One Industry Absolutely Dominates the List of 25 Highest-Paying Jobs in the U.S.
In 5 Words, This Former Netflix Executive Reveals the Key to Employee Motivation
Avoid Making a Bad Sales Hire By Reading Resumes This Way...and weed out the un-hireables in a flash
23 More Exercises to Boost Your Creativity Every Day
This May Be the Best Piece of Email Marketing You'll See This Week (and Maybe Even This Year)
Pink Stopped a Concert to Console a Grieving 14-Year-Old Girl, and It's a Great Lesson In Leadership
Feeling Stuck in a No-Win Situation? These 4 Steps Will Lead You to What's Next
This University Professor Ate at McDonald's for an Entire Month and She Didn't End Up Supersized
Fake Warren Buffett's Twitter Feed Is Suddenly Sharing the Secrets to a Fulfilling Life
Read This List of Books (Suggested by Super-Successful People) to Get Ahead in Business and Life
What's 1 Top Reason for Employees Quitting Their Jobs? Research Says It Comes Down to 2 Words
This Startup Wants to Help You Give Your Employees up to a $4,000 Raise Without Spending a Penny
The Simple Productivity-Boosting Method You're Probably Overlooking
From Bug Zappers to Bedding With Zippers, These Utah Companies Are Growing Like Crazy
After Their Own Manufacturer Betrayed Them With a Copycat Product, These Founders Fought Back
For United Airlines, These 4 Short Words Are Utterly Crucial. (United's President Said Them. But Does He Really Believe Them?)
1 in 5 Americans Have No Retirement Savings. Here's Why Not
Here's the Surprising New Thing American Airlines Is Trying to Make Passengers Hate Flying a Little Bit Less
I Sleep Until Noon and Maybe You Should, Too
Monday, August 27, 2018
Trump Struck a Deal With Mexico That Could Reshape or Possibly Replace NAFTA
Is Google's Flagship Retail Store Coming to Chicago?
1 Surprising Thing That Leaders' Brains Do Differently, According to Science
In 1 Sentence John McCain Explains How to Be a Successful Leader
With 1 Quote John McCain Taught 3 Vital Lessons on What It Means to Be a Leader
Serena Williams's Catsuit Should Make You to Revisit Your Dress Code (Not For the Reason You Think)
Don't Let Lawsuits Destroy Your Business. Here's How to Stay On Track
Entrepreneurs Have High Job Satisfaction, and Their Spouses Should Too
Why Keeping Your Startup Idea to Yourself Is a Horrible Move
This Is How Tech Should Be Evolving Your Business Model
5 Aspects of a Healthy Team Culture You Can't Afford to Ignore
27 Things You Need to Know to Start and Scale a Successful Business
3 Physiological Tricks That Help New Bosses Earn Respect Faster
This 1 Type of Content Will Dramatically Increase Traffic to Your Website
Entrepreneurs, Make the Most of Your Vacation With These Six Tips
From Olympic Diver to Top Tech Executive, This Is the Kind of Leader Every Employee Dreams About
What to Expect from Apple's New iPhones--All 3 of Them
How to Use 'Negative Motivation' to Accomplish Your Goals
Too Much Focus On Metrics Hinders Your Growth. Do This Instead
The People in These Industries Have the Best (and Worst) LinkedIn Profile Photos
5 Ways Solitude Can Make You More Successful, Backed By Science
6 Companies on the Inc. 5000 List That Defy What You Think of High-Growth Companies
33 Years Ago the Father Made a Racist Remark. Now Eli Lilly Diabetes Pulled His Son's Sponsorship. Smart Business?
Facebook Removes 5,000 Ad Filters and Will Soon Start Certifying Advertisers
5 Creative Content Hacks That Build Brand Loyalty
VC Fred Wilson on Duty, Honor, Country
The 10-Minute Daily Meeting That Can Change the Way Your Startup Operates
VC Fred Wilson on Being Public
How to Encourage Every Employee to Speak Up, Share Ideas--and Set Your Organization Up for Success
To Fix Your Toxic Culture, You Must Do 1 Thing: Get A Culture
Want to Make More Friends? Stop Wearing Fancy Clothes and Wear a Walmart T-Shirt, Research Shows
Tom Brady's Opinion on Kneeling for the Anthem Is Pure Emotional Intelligence. You Can Learn From It
Want to Anticipate Problems Before They Happen? Use This Planning Strategy
What Leaders Can Learn About Tenacity From One of the NFL's Most Stunning Comebacks
Marketing to Generation Z? Here's What You Need to Know
Don't Get Stiffed! 7 Ways To Make Sure You're Paid On Time Every Time
This New Research Lab Is Dedicated to Helping Your Workplace Perform Better
Will These Smart Home Gadgets Change Your Life? Try Them to Find Out
Stanford Professor: These 3 Small Actions Make You a Magnet for Attracting Luck
Want to Get an Angel Investor's Attention? This Dollar Shave Club Investor's 10 Rules for Pitching Will Do It
The Comeback Story of Mars Wrigley U.S. President Berta de Pablos-Barbier Will Inspire Your Success
Ever Wonder Why Your Favorite Apps Are Starting to Look the Same? It Might a Good Thing.
How Unconscious Bias Almost Killed My Friend
Are You a Procrastinator? This Simple 5-Minute Trick Will Completely Change Your Life
How One Stylish and Scrappy Startup Designed Its Office in a Single Weekend for $5,000
3 Research Findings That Will Make You a Happier Parent
Get Ready for the World's Shortest Film Festival
Google Helps Its Managers Create a Team Vision With This Simple 5-Step Formula
At 40, He Found Out He Had Parkinson's Disease and Was Fired. Now He Runs a $3.2 Million Company
The 1 Big Mistake Nearly Every Boss Makes, According to LinkedIn CEO Jeff Weiner
This Family Lost Its Footwear Company in the Iranian Revolution. Now, it Makes 1.2 Million Shoes a Year in Georgia
This Change Can Help You Read Faster and Make Your Writing More Readable. But There's a Catch
Infographic: The Traditional Businesses Acquiring Platform Innovation
Was John McCain a True Leader? Read These 8 Sentences to Know for Sure
Sunday, August 26, 2018
4 Myths That Could Be Keeping You From The Success You Seek
Ditch Those Ping-Pong Tables and Embrace the Real Workplace of the Future
Serena Williams Just Proved She Has More Class Than the French Officials Who Banned Her Catsuit
These 30 Seconds Offer John McCain's Most Poignant Lesson in Leadership
You May One Day Have to Live Without Wine, Say Some Experts. Here's Why
3 Ways to Make Anything More Shareable Online
American Airlines CEO Finally Flew in the Airline's New, Maximum Discomfort Planes. Here's His Review
United Airlines CEO: We Don't Hold Aircraft For Anyone (Well, Except For These People)
Southwest Airlines Is About to Charge a Lot More for Something United and American Give Away for Free
How To Hire Friends And Family (Without Ruining Your Relationships and Wrecking Your Business)
19 Wise John McCain Quotes That Will Inspire Your Success and Your Heart
Saturday, August 25, 2018
United Airlines Just Announced Great News For Business Class Passengers. But Will It Mean More Hell In Economy?
Papa John's Takes a Knee and Begs For Forgiveness. A Good Strategy or a Little Desperate?
Mayo Florida Temporarily Changes Name to Miracle Whip, Supposedly Fooling 1,232 Residents
3 Things You Can Learn From the Most Toxic People in the Office
This Is the Most Amazing Photo Ever Taken From a Commercial Airplane. Now, a Southwest Passenger Explains How He Did It
Five Strategies to Help You Manage Well Without Authority
These are the 4 Biggest Innovation Challenges We Must Solve Over the Next Decade
United Airlines Has a 1 Million Mile Contest. The Entries Are Quite Beautiful (It Ends Tuesday)
The Most Potent Gen-Z Entrepreneurial Panel Assembled
At United Airlines, They're Making a Big Change That Will Save Money. It's Quite Brilliant, In Its Way
8 Things to Do Right After Deciding You Want a Career Switch
No, Coffee Is Not a Carcinogen But One Ingredient Can Be Deadly
American Airlines Just Made a Truly Surprising Change. (The Reason Why Is Even More Surprising)
The Way This Famous Airline Handled a Flight Delay Is a Lesson For United, American and Every U.S. Airline
Friday, August 24, 2018
Personal Branding Isn't Rocket Science. But, Doing It Wrong Can Cost You a Job at NASA
How to Lead a Successful Business Meeting Over Drinks
This Successful Young Entrepreneur Has Figured Out and Shares the Secret to Hustle
The Downside of Disruption: Is Your Startup Destined to become a Fad?
3 Questions That Will Immediately Make You a Better Interviewer
Forget Parental Leave. This Company Is Offering 'Fur-ternity' Leave for New Pet Owners
6 Elements of Today's Customer Buying Journey That Can Make or Break Your Business
Amazon Is Paying Twitter 'Ambassadors' to Combat Negative Stories About Working Conditions
Skip the Free Snacks - Here's What Your Tech Startup Should Really Be Investing In
Why Preachers, Teachers, And Savvy Businesses Are Turning to Drake and Cardi B As Sources For Relevant Content
4 Ways to Make Your Career Futureproof
Think the Best Students Skip Going Out to Stay In and Study? New Research Says Think Again
Hiring an HR Leader? Look for a Candidate With These 3 Skills
Amazon Hired People to Defend It From Criticism on Twitter
Women's Equality Day Is Perfect For Kicking Off Company Diversity Initiatives. Here's How to Get Started
Gmail's New 'Confidential Mode' Is Laughably Insecure and Very Silly
Looking to Build Your Network? Please Avoid This 1 Mistake
Top CEOs Warn Changes to Immigration Policy Will Hurt the U.S. Economy
Facebook Hires a New Chief Marketing Officer to Help Fix Its Image
How To Make The Best of The End of Summer
What Hundreds of Giant Reptiles Can Teach Us About Business Planning
Leaning Back is the New Leaning In -- One Expert says All Women Need to do This in the Workplace
A Beginner's Guide to Drawing 2D Graphics With Two.js
Two.js an API that makes it easy to create 2D shapes with code. Follow along and you'll learn how to create and animate shapes from JavaScript.
Two.js is renderer agnostic, so you can rely on the same API to draw with Canvas, SVG, or WebGL. The library has a lot of methods which can be used to control how different shapes appear on the screen or how they are animated.
Installation
The uncompressed version of the library has a size of around 128 KB, while the compressed version is 50 KB. If you are using the latest version, you can further reduce the size of the library using a custom build.
You can either download the minified version of the library from GitHub or you can link directly to the CDN hosted version. Once you have added the library to your webpage, you can start drawing and animating different shapes or objects.
Creating Basic Shapes
First, you need to tell Two.js about the element on which you want to draw and animate your shapes. You can pass some parameters to the Two
constructor to set things up.
Set the type of renderer using the type
property. You can specify a value like svg
, webgl
, canvas
, etc. The type
is set to svg
by default. The width and height of the drawing space can be specified using the width
and height
parameters. You can also set the drawing space to the full available screen using the fullscreen
parameter. When fullscreen
is set to true, the values of width
and height
will be disregarded.
Finally, you can tell Two.js to automatically start an animation with the help of the Boolean autostart
parameter.
After passing all the desired parameters to the constructor, you can start drawing lines, rectangles, circles, and ellipses.
You can draw a line using two.makeLine(x1, y1, x2, y2)
. Here, (x1, y1)
are the coordinates of the first end point, and (x2, y2)
are the coordinates of the second end point. This function will return a Two.Line
object, which can be stored in a variable for further manipulation at a later point.
In a similar manner, you can draw normal and rounded rectangles using two.makeRectangle(x, y, width, height)
and two.makeRoundedRectangle(x, y, width, height, radius)
respectively. Remember that x
and y
determine the center of the rectangle, instead of its top left coordinates like many other libraries. The width
and height
parameters will determine the size of the rectangle. The radius
parameter is used to specify the value of the radius for the rounded corner.
You can also render circles and ellipses on a webpage using two.makeCircle(x, y, radius)
and two.makeEllipse(x, y, width, height)
respectively. Just like the rectangles, the x
and y
parameters specify the center of the circle or ellipse. Setting the width
and height
to the same value in the case of an ellipse will render it like a circle.
One useful method in Two.js that you will use frequently is two.makeGroup(objects)
. You can either pass a list of different objects or pass an array of objects, paths or groups as the parameter to this method. It will also return a Two.Group
object.
Manipulating Objects in a Group
After you have created a group, you can manipulate all its children at once using properties that the group makes available to you.
The stroke
and fill
properties can be used to set the stroke and fill color for all children in a group. They will accept all valid forms in which you can represent a color in CSS. This means that you are free to use RGB, HSL, or hex notation. You can also simply use the name of the color, like orange
, red
, or blue
. Similarly, you can set values for all other properties like linewidth
, opacity
, miter
, and cap
. It is possible to remove the fill and stroke from all children in a group using the noFill()
and noStroke()
methods.
You can also apply other physical transformations like scale
, rotation
, and translation
. These transformations will be applied on individual objects. Adding new objects to a group and removing them is easy with methods like add()
and remove()
.
Defining Gradients and Writing Text
You can define both linear and radial gradients in Two.js. Defining a gradient does not mean that it will be rendered automatically on the screen, but it will be available for you to use when setting the fill
or stroke
values of various objects.
You can define a linear gradient using two.makeLinearGradient(x1, y1, x2, y2, stops)
. The values x1
and y1
determine the coordinates of the start of the gradient. Similarly, the values x2
and y2
determine the coordinates of the end of the gradient. The stops
parameter is an array of Two.Stop
instances. These define the colors of each part of the array and where each color transitions into the next. They can be defined using new Two.Stop(offset, color, opacity)
, where offset
determines the point on the gradient where that particular color has to be fully rendered. The color
parameter determines the color of the gradient at the particular point. You can use any valid CSS color representations as its value. Finally, the opacity
parameter determines the opacity of the color. The opacity is optional, and it can have any value between 0 and 1.
You can define radial gradients in a similar manner using two.makeRadialGradient(x, y, radius, stops, fx, fy)
. In this case, the values x
and y
determine the center of the gradient. The radius
parameter specifies how far the gradient should extend. You can also pass an array of stops to this method in order to set the color composition of the gradients. The parameters fx
and fy
are optional, and they can be used to specify the focal position for the gradient.
Check out some of the types of gradient and their code in the CodePen below.
Remember that the x
and y
position of the gradients are with respect to the origin of the shape they are trying to fill. For instance, a radial gradient which is supposed to fill a shape from the center will always have x
and y
set to zero.
Two.js also allows you to write text on the drawing area and update it later according to your needs. This requires the use of the method two.makeText(message, x, y, styles)
. It might be evident from the name of the parameters that message
is the actual text that you want to write. The parameters x
and y
are the coordinates of the point which will act as the center for writing the text. The styles
parameter is an object which can be used to set the values of a large set of properties.
You can use styles to set the values of properties like font family
, size
, and alignment
. You can also specify the value of properties like fill
, stroke
, opacity
, rotation
, scale
, and translation
.
Creating a Two.js Project
After learning about all these methods and properties, it is time to apply them to a project. In this tutorial, I will show you how we can use Two.js to render the first ten elements of the periodic table with electrons rotating around the nucleus. The nucleus will also have some slight movement to improve the visual appeal of our representation.
We begin by defining some variables and functions which will be used later.
var centerX = window.innerWidth / 2; var centerY = window.innerHeight / 2; var elem = document.getElementById("atoms"); var elementNames = [ "", "Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon" ]; var styles = { alignment: "center", size: 36, family: "Lato" }; var nucleusCount = 10; var nucleusArray = Array(); var electronCount = 10; var electronArray = Array(); function intRange(min, max) { return Math.random() * (max - min) + min; }
The above code stores the coordinates of the center of our window in the variables centerX
and centerY
. These will be used later to place our atom in the center. The elementNames
array contains the names of the first ten elements of the periodic table. The index of each name corresponds to the number of electrons and protons of that element, and it begins with an empty string. The styles
object contains properties for styling the text object.
We have also defined a function intRange()
to get a random integer value within given extremes.
var two = new Two({ fullscreen: true }).appendTo(elem); var protonColor = two.makeRadialGradient( 0, 0, 15, new Two.Stop(0, "red", 1), new Two.Stop(1, "black", 1) ); var neutronColor = two.makeRadialGradient( 0, 0, 15, new Two.Stop(0, "blue", 1), new Two.Stop(1, "black", 1) ); for (i = 0; i < nucleusCount; i++) { nucleusArray.push(two.makeCircle(intRange(-10, 10), intRange(-10, 10), 8)); } nucleusArray.forEach(function(nucleus, index) { if (index % 2 == 0) { nucleus.fill = protonColor; } if (index % 2 == 1) { nucleus.fill = neutronColor; } nucleus.noStroke(); });
This creates an instance of Two and defines two radial gradients. The red/black radial gradients will represent protons, and blue/black gradients will represent neutrons.
We have used the intRange()
function to place all these neutrons and protons within 20 pixels of each other. The makeCircle()
method also sets the radius of these protons and neutrons to 10 pixels. After that, we iterate over nucleusArray
and fill each circle with a different gradient alternately.
for (var i = 0; i < 10; i++) { if (i < 2) { var shellRadius = 50; var angle = i * Math.PI; electronArray.push( two.makeCircle( Math.cos(angle) * shellRadius, Math.sin(angle) * shellRadius, 5 ) ); } if (i >= 2 && i < 10) { var shellRadius = 80; var angle = (i - 2) * Math.PI / 4; electronArray.push( two.makeCircle( Math.cos(angle) * shellRadius, Math.sin(angle) * shellRadius, 5 ) ); } }
Placing neutrons and protons inside the nucleus was easy. However, properly placing the electrons at a uniform distance will require a little maths. We use the shellRadius
variable to specify the distance of different electron shells from the nucleus. A whole circle covers an angle equal to 2 PI radians. We can place different electrons uniformly by distributing the 2 PI radians between them equally.
The Math.cos()
and Math.sin()
functions are used to separate the vertical and horizontal components of the position vector of different electrons based on their angle.
var orbitA = two.makeCircle(centerX, centerY, 50); orbitA.fill = "transparent"; orbitA.linewidth = 2; orbitA.stroke = "rgba(0, 0, 0, 0.1)"; var orbitB = two.makeCircle(centerX, centerY, 80); orbitB.fill = "transparent"; orbitB.linewidth = 2; orbitB.stroke = "rgba(0, 0, 0, 0.1)"; var groupElectronA = two.makeGroup(electronArray.slice(0, 2)); groupElectronA.translation.set(centerX, centerY); groupElectronA.fill = "orange"; groupElectronA.linewidth = 1; var groupElectronB = two.makeGroup(electronArray.slice(2, 10)); groupElectronB.translation.set(centerX, centerY); groupElectronB.fill = "yellow"; groupElectronB.linewidth = 1; var groupNucleus = two.makeGroup(nucleusArray); groupNucleus.translation.set(centerX, centerY);
This part of the code puts electrons from different shells as well as neutrons and protons in their own separate groups. It also sets the fill colors for all electrons in a specific orbit at once.
two .bind("update", function(frameCount) { groupElectronA.rotation += 0.025 * Math.PI; groupElectronB.rotation += 0.005 * Math.PI; groupNucleus.rotation -= 0.05; }) .play(); var text = two.makeText("", centerX, 100, styles); nucleusArray.forEach(function(nucleus, index) { nucleus.opacity = 0; }); electronArray.forEach(function(electron, index) { electron.opacity = 0; });
This part of the code sets the opacity of individual electrons and protons to zero. It also tells Two.js to rotate the electrons and protons at specific speeds.
visible = 0; document.addEventListener("click", function(event) { if (visible < nucleusArray.length) { nucleusArray[visible].opacity = 1; electronArray[visible].opacity = 1; visible++; text.value = elementNames[visible]; } else { nucleusArray.forEach(el => el.opacity=0); electronArray.forEach(el => el.opacity=0); visible = 0; text.value = elementNames[0]; } });
The final part of the code allows us to iterate through the elements by clicking the mouse or tapping. To load the next element, we make one more electron and one more proton or neutron visible and update the element name. After clicking on the last element, all the particles are hidden again so we can start over. The visible
variable keeps track of the number of atomic particles that are currently visible so that we can show or hide them accordingly.
Try clicking or tapping in the following CodePen demo to see the first ten elements of the periodic table.
Final Thoughts
We began this tutorial with a brief introduction to the Two.js library and how it can be used to draw shapes like rectangles, circles, and ellipses. After that, we discussed how we can group different objects together to manipulate them all at once. We used this ability to group elements to translate and rotate them in synchronization. These tools all came together in our animation of the atoms of the first ten elements in the periodic table.
As you can see, creating animated 2D graphics is very easy using Two.js. The focus of this post was to help you get started quickly, so we only covered the basics. However, you should read the official documentation to learn more about the library!
More China Tariffs? Why Some Business Owners Say Bring Them On
This Study of 1.2 Million People Reveals the 1 Exercise That Most Improves Overall Mental Health
Stop Believing You Have the Same 24 Hours as Beyonce
Hindsight is 20/20: Insights and Growth Hacks from a Self-Described Accidental Entrepreneur
When to Take Your B2B Brand From 'Good Enough' to 'Amazing'
Is Money Tight at Your Business? Try Bartering Instead--Here's How
What's the Secret Sauce That Turns Skepticism to Success? A New Harvard Study Explains
Sitting Near a Multitasker Decreases Your Intelligence By 17 Percent
Delta's CEO Just Offered a Superb Lesson in What It Means to be a Leader Today (the NRA Won't Like It)
Southwest Airlines Bans Peanuts (But Your Trained Service Miniature Horse Is OK)
How Evil Are You? Psychologists Have Developed an IQ-Like Test to Measure Your 'Dark Core'
4 Elements of a Great Pitch--Thanks to the Female Founder of a $3 Billion Startup
Want to Raise Your Emotional Intelligence? Avoid These 11 Behaviors
How the 90/90 Rule Could Save Tesla
How This Couple Combined Their Expertise to Become a Major Contractor for the Government
Putting This 1 Thing in Place Can Make Breaking Up With Your Co-Founder Easier
A Big New Study Says the Least Sexist States Are Among the More Conservative (You Read That Right)
Steve Jobs Was a Creative Genius. Steve Jobs Was a Total Jerk
Thursday, August 23, 2018
How One Young Woman Lost Her Dream Job and Learned the Hard Way to Be More Cautious on Twitter
Influencer Marketing: Apple v Samsung, Canon v Nikon, Amazon v Google, and Oculus v Vive
This is 1 of the Biggest Mistakes Marketers and Brands Make with their Content
Avoid These Top 5 Mistakes With Your Company's Messaging Platform
5 Expert-Approved Habits to Improve Brain Health
9 Things You Need To Do If You Want Your Corporate Event To Succeed
5 Ways to Boost Your Employees' Morale That Doesn't Involve a Job Promotion
As This Plane Takes Off, An Engine Catches Fire. Naturally, Passengers Start Filming
Kroger Just Made a Huge Announcement That Will Have Other Supermarkets Wondering What Happened
Newsrooms Are Shrinking--Especially After More Recent Layoffs. Use These 4 Strategies to Get Your Story Out Anyway
How to Make the Most Out of That Work Trip
3 Unique Challenges Women CEOs Face Today
$3.2 Billion Autonomous Car Startup Zoox Suddenly Fired Its CEO and Won't Explain Why
Lyft to Offer Free and Discounted Rides on Election Day
How to Improve Your Leadership Skills for Different Scenarios
Code Your First API With Node.js and Express: Set Up the Server
How to Set Up an Express API Server in Node.js
In the previous tutorial, we learned what the REST architecture is, the six guiding constraints of REST, how to understand HTTP request methods and their response codes, and the anatomy of a RESTful API endpoint.
In this tutorial, we'll set up a server for our API to live on. You can build an API with any programming language and server software, but we will use Node.js, which is the back-end implementation of JavaScript, and Express, a popular, minimal framework for Node.
Installation
Our first prerequisite is making sure Node.js and npm are installed globally on the computer. We can test both using the -v
flag, which will display the version. Open up your command prompt and type the following.
node -v && npm -v
v10.8.0 6.2.0
Your versions may be slightly different than mine, but as long as both are there, we can get started.
Let's create a project directory called express-api
and move to it.
mkdir express-api && cd express-api
Now that we're in our new directory, we can initialize our project with the init command.
npm init
This command will prompt you to answer some questions about the project, which you can choose to fill out or not. Once the setup is complete, you'll have a package.json file that looks like this:
{ "name": "express-api", "version": "1.0.0", "description": "Node.js and Express REST API", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Tania Rascia", "license": "MIT" }
Now that we have our package.json, we can install the dependencies required for our project. Fortunately we don't require too many dependencies, just these four listed below.
- body-parser: Body parsing middleware.
- express: A minimalist web framework we'll use for our server.
- mysql: A MySQL driver.
- request (optional): A simple way to make HTTP calls.
We'll use the install
command followed by each dependency to finish setting up our project.
npm install body-parser express mysql request
This will create a package-lock.json file and a node_modules directory, and our package.json will be updated to look something like this:
{ "name": "express-api", "version": "1.0.0", "description": "Node.js and Express REST API", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Tania Rascia", "license": "MIT", "dependencies": { "dependencies": { "body-parser": "^1.18.3", "express": "^4.16.3", "mysql": "^2.16.0", "request": "^2.88.0" } }
Setting Up an HTTP Server
Before we get started on setting up an Express server, we will quickly set up an HTTP server with Node's built-in http
module, to get an idea of how a simple server works.
Create a file called hello-server.js. Load in the http
module, set a port number (I chose 3001
), and create the server with the createServer()
method.
// Build a server with Node's HTTP module const http = require('http'); const port = 3001; const server = http.createServer();
In the introductory REST article, we discussed what requests and responses are with regards to an HTTP server. We're going to set our server to handle a request and display the URL requested on the server side, and display a Hello, server! message to the client on the response side.
server**on('request'** (request, response) => { console.log(`URL: ${request.url}`); response.end('Hello, server!') })
Finally, we will tell the server which port to listen on, and display an error if there is one.
// Start the server server.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server is listening on port ${port}`) })
Now, we can start our server with node
followed by the filename.
node hello-server.js
You will see this response in the terminal:
Server is listening on port 3001
To check that the server is actually running, go to http://localhost:3001/
in your browser's address bar. If all is working properly, you should see Hello, server! on the page. In your terminal, you'll also see the URLs that were requested.
URL: / URL: /favicon.ico
If you were to navigate to http://localhost:3001/hello
, you would see URL: /hello
.
We can also use cURL on our local server, which will show us the exact headers and body that are being returned.
curl -i http://localhost:3001
HTTP/1.1 200 OK Date: Wed, 15 Aug 2018 22:14:23 GMT Connection: keep-alive Content-Length: 14 Hello, server!
If you close the terminal window at any time, the server will go away.
Now that we have an idea of how the server, request, and response all work together, we can rewrite this in Express, which has an even simpler interface and extended features.
Setting Up an Express Server
We're going to create a new file, app.js, which will be the entry point to our actual project. Just like with the original http server, we'll require a module and set a port to start.
Create an app.js file and put the following code in it.
// Require packages and set the port const express = require('express'); const port = 3002; const app = express();
Now, instead of looking for all requests, we will explicitly state that we are looking for a GET
request on the root of the server (/
). When /
receives a request, we will display the URL requested and the "Hello, Server!" message.
app.get('/', (request, response) => { console.log(`URL: ${request.url}`); response.send('Hello, Server!'); });
Finally, we'll start the server on port 3002
with the listen()
method.
// Start the server const server = app.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server listening on port ${server.address().port}`); });
We can start the server with node app.js
as we did before, but we can also modify the scripts
property in our package.json file to automatically run this specific command.
"scripts": { "start": "node app.js" },
Now we can use npm start
to start the server, and we'll see our server message in the terminal.
Server listening on port 3002
If we run a curl -i
on the URL, we will see that it is powered by Express now, and there are some additional headers such as Content-Type
.
curl -i http://localhost:3002
HTTP/1.1 200 OK X-Powered-By: Express Content-Type: text/html; charset=utf-8 Content-Length: 14 ETag: W/"e-gaHDsc0MZK+LfDiTM4ruVL4pUqI" Date: Wed, 15 Aug 2018 22:38:45 GMT Connection: keep-alive Hello, Server!
Add Body Parsing Middleware
In order to easily deal with POST
and PUT
requests to our API, we will add body parsing middleware. This is where our body-parser
module comes in. body-parser
will extract the entire body of an incoming request and parse it into a JSON object that we can work with.
We'll simply require the module at the top of our file. Add the following require
statement to the top of your app.js file.
const bodyParser = require('body-parser'); ...
Then we'll tell our Express app to use body-parser
, and look for JSON.
// Use Node.js body parsing middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true, }));
Also, let's change our message to send a JSON object as a response instead of plain text.
response.send({message: 'Node.js and Express REST API'});
Following is our full app.json file as it stands now.
// Require packages and set the port const express = require('express'); const port = 3002; const bodyParser = require('body-parser'); const app = express(); // Use Node.js body parsing middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true, })); app.get('/', (request, response) => { response.send({ message: 'Node.js and Express REST API'} ); }); // Start the server const server = app.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server listening on port ${server.address().port}`); });
If you send a curl -i
to the server, you'll see that the header now returns Content-Type: application/json; charset=utf-8
.
Set Up Routes
So far, we only have a GET
route to the root (/
), but our API should be able to handle all four major HTTP request methods on multiple URLs. We're going to set up a router and make some fake data to display.
Let's create a new directory called routes, and a file within called routes.js. We'll link to it at the top of app.js.
const routes = require('./routes/routes');
Note that the .js
extension is not necessary in the require. Now we'll move our app's GET
listener to routes.js. Enter the following code in routes.js.
const router = app => { app.get('/', (request, response) => { response.send({ message: 'Node.js and Express REST API' }); }); }
Finally, export the router
so we can use it in our app.js file.
// Export the router module.exports = router;
In app.js, replace the app.get()
code you had before with a call to routes()
:
routes(app);
You should now be able to go to http://localhost:3002
and see the same thing as before. (Don't forget to restart the server!)
Once that is all set up and working properly, we'll serve some JSON data with another route. We'll just use fake data for now, since our database is not yet set up.
Let's create a users
variable in routes.js, with some fake user data in JSON format.
const users = [{ id: 1, name: "Richard Hendricks", email: "richard@piedpiper.com", }, { id: 2, name: "Bertram Gilfoyle", email: "gilfoyle@piedpiper.com", }, ];
We'll add another GET
route to our router, /users
, and send the user data through.
app.get('/users', (request, response) => { response.send(users); });
After restarting the server, you can now navigate to http://localhost:3002/users
and see all our data displayed.
Note: If you do not have a JSON viewer extension on your browser, I highly recommend you download one, such as JSONView for Chrome. This will make the data much easier to read!
Visit our GitHub Repo to see the completed code for this post and compare it to your own.
Conclusion
In this tutorial, we learned how to set up a built-in HTTP server and an Express server in node, route requests and URLs, and consume JSON data with get requests.
In the final installment of the RESTful API series, we will hook up our Express server to MySQL to create, view, update, and delete users in a database, finalizing our API's functionality.