Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 40307db

Browse files
committedJun 22, 2016
Ready to stage
1 parent 8ecf23e commit 40307db

File tree

6 files changed

+285
-11
lines changed

6 files changed

+285
-11
lines changed
 

‎articles/cdn/cdn-app-dev-node.md

Lines changed: 285 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,13 @@ You will then be presented a series of questions to initialize your project. Fo
3838

3939
![NPM init output](./media/cdn-app-dev-node/cdn-npm-init.png)
4040

41-
Our project is now initialized with a *packages.json* file. Our project is going to use some Azure libraries contained in NPM packages. Let's add those to the project as dependencies.
41+
Our project is now initialized with a *packages.json* file. Our project is going to use some Azure libraries contained in NPM packages. We'll be using the Azure Client Runtime for Node.js (ms-rest-azure) and the Azure CDN Client Library for Node.js (azure-arm-cd). Let's add those to the project as dependencies.
4242
```
4343
npm install --save ms-rest-azure
4444
npm install --save azure-arm-cdn
4545
```
4646

47-
Assuming the packages installed with no errors, if we view the *package.json* file, it should look similar to this (version numbers may differ):
47+
After the packages are done installing, the *package.json* file should look similar to this (version numbers may differ):
4848

4949
```
5050
{
@@ -66,26 +66,300 @@ Assuming the packages installed with no errors, if we view the *package.json* fi
6666

6767
Finally, using your text editor, create a blank text file and save it in the root of our project folder as *app.js*. We're now ready to begin writing code.
6868

69-
##
69+
## Requires, constants, authentication, and structure
70+
71+
Let's get the basic structure of our program written.
72+
73+
1. Add the "requires" for our NPM packages at the top with the following:
74+
75+
```
76+
var msRestAzure = require('ms-rest-azure');
77+
var cdnManagementClient = require('azure-arm-cdn');
78+
```
79+
80+
2. We need to define some constants our methods will use. Add the following. Be sure to replace the placeholders, including the **<angle brackets>**, with your own values as needed.
81+
82+
```
83+
//Tenant app constants
84+
const clientId = "<YOUR CLIENT ID>";
85+
const clientSecret = "<YOUR CLIENT AUTHENTICATION KEY>"; //Only for service principals
86+
const tenantId = "<YOUR TENANT ID>";
87+
88+
//Application constants
89+
const subscriptionId = "<YOUR SUBSCRIPTION ID>";
90+
const resourceGroupName = "CdnConsoleTutorial";
91+
const resourceLocation = "<YOUR PREFERRED AZURE LOCATION, SUCH AS Central US>";
92+
```
93+
94+
3. Next, we'll instantiate the CDN management client and give it our credentials.
95+
96+
```
97+
var credentials = new msRestAzure.ApplicationTokenCredentials(clientId, tenantId, clientSecret);
98+
var cdnClient = new cdnManagementClient(credentials, subscriptionId);
99+
```
100+
101+
If you are using individual user authentication, these two lines will look slightly different.
102+
103+
>[AZURE.IMPORTANT] Only use this code sample if you are choosing to have individual user authentication instead of a service principal.
104+
105+
```
106+
var credentials = new msRestAzure.UserTokenCredentials(clientId, 
107+
tenantId, '<username>', '<password>', '<redirect URI>');
108+
var cdnClient = new cdnManagementClient(credentials, subscriptionId);
109+
```
110+
111+
Be sure to replace the items in **&lt;angle brackets&gt;** with the correct information. For `<redirect URI>`,use the redirect URI you entered when you registered the application in Azure AD.
112+
113+
114+
4. Our Node.js console application is going to take some command line parameters. Let's validate that at least one parameter was passed.
115+
116+
```
117+
//Collect command line parameters
118+
var parms = process.argv.slice(2);
119+
120+
//Do we have parameters?
121+
if(parms == null || parms.length == 0)
122+
{
123+
console.log("Not enough parameters!");
124+
console.log("Valid commands are list, delete, create, and purge.");
125+
process.exit(1);
126+
}
127+
```
128+
129+
5. That brings us to the main part of our program, where we'll branch off to other functions based on what parameters were passed.
130+
131+
```
132+
switch(parms[0].toLowerCase())
133+
{
134+
case "list":
135+
cdnList();
136+
break;
137+
138+
case "create":
139+
cdnCreate();
140+
break;
141+
142+
case "delete":
143+
cdnDelete();
144+
break;
145+
146+
case "purge":
147+
cdnPurge();
148+
break;
149+
150+
default:
151+
console.log("Valid commands are list, delete, create, and purge.");
152+
process.exit(1);
153+
}
154+
```
155+
156+
6. At several places in our program, we'll need to make sure the right number of parameters were passed in and display some help if they don't look correct. Let's create functions to do that.
157+
158+
```
159+
function requireParms(parmCount) {
160+
if(parms.length < parmCount) {
161+
usageHelp(parms[0].toLowerCase());
162+
process.exit(1);
163+
}
164+
}
165+
166+
function usageHelp(cmd) {
167+
console.log("Usage for " + cmd + ":");
168+
switch(cmd)
169+
{
170+
case "list":
171+
console.log("list profiles");
172+
console.log("list endpoints <profile name>");
173+
break;
174+
175+
case "create":
176+
console.log("create profile <profile name>");
177+
console.log("create endpoint <profile name> <endpoint name> <origin hostname>");
178+
break;
179+
180+
case "delete":
181+
console.log("delete profile <profile name>");
182+
console.log("delete endpoint <profile name> <endpoint name>");
183+
break;
184+
185+
case "purge":
186+
console.log("purge <profile name> <endpoint name> <path>");
187+
break;
188+
189+
default:
190+
console.log("Invalid command.");
191+
}
192+
}
193+
```
194+
195+
7. Finally, the functions we'll be using on CDN management client are asynchronous, so they need a method to callback when they're done. Let's make one that can display the output from the CDN management client (if any) and exit the program gracefully.
196+
197+
```
198+
function callback(err, result, request, response) {
199+
if (err) {
200+
console.log(err);
201+
process.exit(1);
202+
} else {
203+
console.log((result == null) ? "Done!" : result);
204+
process.exit(0);
205+
}
206+
}
207+
```
208+
209+
Now that the basic structure of our program is written, we should create the functions called based on our parameters.
210+
211+
## List CDN profiles and endpoints
212+
213+
Let's start with code to list our existing profiles and endpoints. I'll provide code comments with the expected syntax so we know which parameter goes where.
214+
215+
```
216+
// list profiles
217+
// list endpoints <profile name>
218+
function cdnList(){
219+
requireParms(2);
220+
switch(parms[1].toLowerCase())
221+
{
222+
case "profiles":
223+
console.log("Listing profiles...")
224+
cdnClient.profiles.listByResourceGroup(resourceGroupName, callback);
225+
break;
226+
227+
case "endpoints":
228+
requireParms(3)
229+
console.log("Listing endpoints...")
230+
cdnClient.endpoints.listByProfile(parms[2], resourceGroupName, callback);
231+
break;
232+
233+
default:
234+
console.log("Invalid parameter.");
235+
process.exit(1);
236+
}
237+
}
238+
```
239+
240+
## Create CDN profiles and endpoints
241+
242+
Next, we'll write the functions to create profiles and endpoints.
243+
244+
```
245+
function cdnCreate() {
246+
requireParms(2);
247+
switch(parms[1].toLowerCase())
248+
{
249+
case "profile":
250+
cdnCreateProfile();
251+
break;
252+
253+
case "endpoint":
254+
cdnCreateEndpoint();
255+
break;
256+
257+
default:
258+
console.log("Invalid parameter.");
259+
process.exit(1);
260+
}
261+
}
262+
263+
// create profile <profile name>
264+
function cdnCreateProfile() {
265+
requireParms(3);
266+
console.log("Creating profile...")
267+
var standardCreateParameters = {
268+
location: resourceLocation,
269+
sku: {
270+
name: 'Standard_Verizon'
271+
}
272+
};
273+
274+
cdnClient.profiles.create(parms[2], standardCreateParameters, resourceGroupName, callback);
275+
}
276+
277+
// create endpoint <profile name> <endpoint name> <origin hostname>
278+
function cdnCreateEndpoint() {
279+
requireParms(5);
280+
console.log("Creating endpoint...")
281+
var endpointProperties = {
282+
location: resourceLocation,
283+
origins: [{
284+
name: parms[4],
285+
hostName: parms[4]
286+
}]
287+
}
288+
289+
cdnClient.endpoints.create(parms[3], endpointProperties, parms[2], resourceGroupName, callback);
290+
}
291+
```
292+
293+
## Purge an endpoint
294+
295+
Assuming the endpoint has been created, one common task that we might want to perform in our program is purging content in our endpoint.
296+
297+
```
298+
// purge <endpoint name> <path>
299+
function cdnPurge() {
300+
requireParms(4);
301+
console.log("Purging endpoint...")
302+
var purgeContentPaths = [ parms[3] ];
303+
  cdnClient.endpoints.purgeContent(parms[2], parms[1], resourceGroupName, purgeContentPaths, callback);
304+
}
305+
```
306+
307+
## Delete CDN profiles and endpoints
308+
309+
The last function we will include deletes endpoints and profiles.
310+
311+
```
312+
function cdnDelete() {
313+
requireParms(2);
314+
switch(parms[1].toLowerCase())
315+
{
316+
// delete profile <profile name>
317+
case "profile":
318+
requireParms(3);
319+
console.log("Deleting profile...")
320+
cdnClient.profiles.deleteIfExists(parms[2], resourceGroupName, callback);
321+
break;
322+
323+
// delete endpoint <profile name> <endpoint name>
324+
case "endpoint":
325+
requireParms(4)
326+
console.log("Deleting endpoint...")
327+
cdnClient.endpoints.deleteIfExists(parms[3], parms[2], resourceGroupName, callback);
328+
break;
329+
330+
default:
331+
console.log("Invalid parameter.");
332+
process.exit(1);
333+
}
334+
}
335+
```
70336
71337
## Running the program
72338
73-
We can now compile and run the program by clicking the **Start** button in Visual Studio.
339+
We can now execute our Node.js program using our favorite debugger or at the console.
340+
341+
> [AZURE.TIP] If you're using Visual Studio Code as your debugger, you'll need to setup your environment to pass in the command line parameters. Visual Studio Code does this in the **lanuch.json** file. Look for a property named **args** and add an array of string values for your parameters, so that it looks similar to this: `"args": ["list", "profiles"]`.
342+
343+
Let's start by listing our profiles.
344+
345+
![List profiles](./media/cdn-app-dev-node/cdn-list-profiles.png)
346+
347+
We got back an empty array. Since we don't have any profiles in our resource group, that's expected. Let's create a profile now.
74348
75-
![Program running](./media/cdn-app-dev-net/cdn-program-running-1.png)
349+
![Create profile](./media/cdn-app-dev-node/cdn-create-profile.png)
76350
77-
When the program reaches the above prompt, you should be able to return to your resource group in the Azure Portal and see that the profile has been created.
351+
Now, let's add an endpoint.
78352
79-
![Success!](./media/cdn-app-dev-net/cdn-success.png)
353+
![Create endpoint](./media/cdn-app-dev-node/cdn-create-endpoint.png)
80354
81-
We can then confirm the prompts to run the rest of the program.
355+
Finally, let's delete our profile.
82356
83-
![Program completing](./media/cdn-app-dev-net/cdn-program-running-2.png)
357+
![Delete profile](./media/cdn-app-dev-node/cdn-delete-profile.png)
84358
85359
## Next Steps
86360
87-
To see the completed project from this walkthrough, [download the sample](https://code.msdn.microsoft.com/Azure-CDN-Management-1f2fba2c).
361+
To see the completed project from this walkthrough, [download the sample](https://code.msdn.microsoft.com/Azure-CDN-SDK-for-Nodejs-c712bc74).
88362
89-
To find additional documentation on the Azure CDN Management Library for .NET, view the [reference on MSDN](https://msdn.microsoft.com/library/mt657769.aspx).
363+
To find additional documentation on the Azure SDK for Node.js, view the [documentation](http://azure.github.io/azure-sdk-for-node/).
90364
91365
Loading
Loading
Loading
Loading
Loading

0 commit comments

Comments
 (0)
Please sign in to comment.