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

Writing the file in the playground folder

Let's go ahead and comment out all the code we have so far and start with a clean slate. First up, let's go ahead and load in the fs module. The const variable fs will be set equal to require, and we'll pass the fs module that we've used in the past, as shown here:

// var obj = {
// name: 'Andrew'
// };
// var stringObj = JSON.stringify(obj);
// console.log(typeof stringObj);
// console.log(stringObj);

// var personString = '{"name": "Andrew","age": 25}';
// var person = JSON.parse(personString);
// console.log(typeof person);
// console.log(person);

const fs = require('fs');

The next thing we'll do is define the object. This object will be stored inside of our file, and then will be read back and parsed. This object will be a variable called originalNote, and we'll call it originalNote because later on, we'll load it back in and call that variable Note.

Now, originalNote will be a regular JavaScript object with two properties. We'll have the title property, which we'll set equal to Some title, and the body property, which we will set equal to Some body, as shown here:

var originalNote = {
title: 'Some title',
body: 'Some body'
};

The next step that you will need to do is take the original note and create a variable called originalNoteString, and set that variable equal to the JSON value of the object we defined earlier. This means that you'll need to use one of the two JSON methods we used previously in this section.

Now, once you have that originalNoteString variable, we can write a file to the filesystem. I'll write that line for you, fs.writeFileSync. The writeFileSync method, which we used before, takes two arguments. One will be the filename, and since we're using JSON, it's important to use the JSON file extension. I'll call this file notes.json. The other arguments will be text content, originalNoteString, which is not yet defined, as shown in this code block:

// originalNoteString
fs.writeFileSync('notes.json', originalNoteString);

This is the first step to the process; this is how we'll write that file into the playground folder. The next step to the process will be to read out the contents, parse it using the JSON method earlier, and print one of the properties to the screen to make sure that it's an object. In this case, we'll print the title.

主站蜘蛛池模板: 江永县| 荆门市| 澄江县| 淳安县| 敦化市| 黎平县| 邢台市| 靖宇县| 江都市| 巫山县| 海盐县| 灵石县| 大余县| 安仁县| 长沙县| 东宁县| 威信县| 辉县市| 儋州市| 奎屯市| 迁安市| 巨野县| 鄢陵县| 株洲县| 资源县| 宜阳县| 康定县| 洪洞县| 尤溪县| 泗洪县| 沈丘县| 绥棱县| 海原县| 庄河市| 台中市| 中阳县| 柯坪县| 寻甸| 无极县| 东丰县| 泸州市|