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

A simple example of the working of the exports object

Let's take a quick look at how that works. What we'll do is to define an age property using module.exports, the object we just explored over in Terminal. Also, we know that it's an object because we can see it in the preceding screenshot (exports: {}); this means that I can add a property, age, and set it equal to my age, which is 25, as shown here:

console.log('Starting notes.js');

module.exports.age = 25;

Then I can save this file and move into app.js to take advantage of this new age property. The const variable notes will be storing all of my exports, in the present case, just age.

In fs.appendFile, after the greeting.txt file, I'll add You are followed by the age. Inside template strings, we will use $ with curly braces, notes.age, and a period at the end, as shown here:

console.log('Starting app.js');

const fs = require('fs');
const os = require('os');
const notes = require('./notes.js');

var user = os.userInfo();

fs.appendFile('greetings.txt', `Hello ${user.username}! You are ${notes.age}.`);

Now our greeting should say Hello Gary! You are 25. It's getting the 25 value from our separate file (that is, note.js), which is fantastic.

Let's take a quick moment to rerun the program over in Terminal using the up arrow key and enter keys:

Back inside the app, we can open greetings.txt, and as shown in the following screenshot, we have Hello Gary! You are 25:

Using require(), we were able to require a file that we created, and this file stored some properties that were advantageous to the rest of the project.

主站蜘蛛池模板: 巴楚县| 陵川县| 天水市| 宾阳县| 阜新市| 靖西县| 松潘县| 潼南县| 金塔县| 阿勒泰市| 马龙县| 宁明县| 将乐县| 建昌县| 常熟市| 曲周县| 乐山市| 淮安市| 枝江市| 如东县| 绵阳市| 勃利县| 霍城县| 乡城县| 华宁县| 长沙县| 岳阳县| 神农架林区| 三门县| 遂宁市| 邛崃市| 平凉市| 山丹县| 辽源市| 永胜县| 长兴县| 白朗县| 时尚| 张家界市| 富平县| 阿克苏市|