- Beginning API Development with Node.js
- Anthony Nandaa
- 291字
- 2021-07-23 17:21:48
Activity: Running Basic Node.js Code
Before You Begin
Open the IDE and the Terminal to implement this solution.
Aim
Learn how to write a basic Node.js file and run it.
Scenario
You are writing a very basic mathematical library with handy mathematical functions.
Steps for Completion
- Create your project directory (folder), where all the code for this and other chapters will be kept. You can call it beginning-nodejs for brevity. Inside this directory, create another directory named lesson-1, and inside that, create another directory called activity-a. All this can be done using the following command:
mkdir -p beginning-nodejs/lesson-1/activity-a
- Inside activity-a, create a file using touch maths.js command.
- Inside this file, create the following functions:
- add: This takes any two numbers and returns the sum of both, for example, add(2, 5) returns 7
- sum: Unlike add, takes any number of numbers and returns their sum, for example, sum(10, 5, 6) returns 21
- After these functions, write the following code to act as tests for your code:
console.log(add(10, 6)); // 16
console.log(sum(10, 5, 6)); // 21
- Now, on the Terminal, change directory to lesson-1. That's where we will be running most of our code from for the whole chapter.
- To run the code, run the following command:
node activity-a/math.js
The 16 and 21 values should be printed out on the Terminal.
Even though you can configure the IDE so that Node.js code be run at the click of a button, it's strongly recommend that you run the code from the Terminal to appreciate how Node.js actually works.
For uniformity, if you are using a Windows machine, then run your commands from the Git Bash Terminal.
For the reference solution, use the math.js file at Code/Lesson-1/activity-solutions/activity-a.
For uniformity, if you are using a Windows machine, then run your commands from the Git Bash Terminal.
For the reference solution, use the math.js file at Code/Lesson-1/activity-solutions/activity-a.