官术网_书友最值得收藏!

Using template strings

The second way to swap world with user.username in the fs.appendFile is, using an ES6 feature known as template strings. Template strings start and end with the ` (tick) operator, which is available to the left of the 1 key on your keyboard. Then you type things as you normally would.

This means that we'll first type hello, then we'll add a space with the ! (exclamation) mark, and just before !, we will put the name:

console.log('Starting app.');

const fs = require('fs');
const os = require('os');

var user = os.userInfo();

fs.appendFile('greetings.txt', `Hello !`);

To insert a JavaScript variable inside your template string, you use the $ (dollar) sign followed by opening and closing curly braces. Then we will just reference a variable such as user.username:

console.log('Starting app.');

const fs = require('fs');
const os = require('os');

var user = os.userInfo();

fs.appendFile('greetings.txt', `Hello ${user.username}!`);
Notice that the Atom editor actually picks up on the syntax of curly braces.

This is all it takes to use template strings; it's an ES6 feature available because you're using Node v6. This syntax is much easier to understand and update than the string/concatenation version we saw earlier.

If you run the code, it will produce the exact same output. We can run it, view the text file, and this time around, we have Hello Gary! twice, which is what we want here:

With this in place, we are now done with our very basic example and we're ready to start creating our own files for our notes application and requiring them inside app.js in the next section.

First up, you learned that we can use require to load in modules. This lets us take existing functionality written by either the Node developers, a third-party library, or ourselves, and load it into a file so that it can be reusable. Creating reusable code is essential for building large apps. If you have to build everything in an app every time, no one would ever get anything done because they would get stuck at building the basics, things such as HTTP servers and web servers. There are already modules for such stuff, and we'll be taking advantage of the great npm community. In this case, we used two built-in modules, fs and os. We loaded them in using require and we stored the module results inside two variables. These variables store everything available to us from the module; in the case of fs, we use the appendFile method, and in the case of OS, we use the userInfo method. Together, we were able to grab the username and save it into a file, which is fantastic.

主站蜘蛛池模板: 大新县| 竹山县| 荔浦县| 政和县| 龙陵县| 诏安县| 咸阳市| 渑池县| 金平| 盖州市| 长顺县| 阜康市| 安义县| 贵德县| 宿州市| 威海市| 揭西县| 贡觉县| 察隅县| 波密县| 台江县| 金沙县| 昂仁县| 白河县| 洮南市| 临安市| 英德市| 永丰县| 德安县| 呼伦贝尔市| 六盘水市| 呈贡县| 汕头市| 辽宁省| 日喀则市| 高唐县| 河西区| 崇左市| 辉南县| 奉贤区| 略阳县|