Home Logic LAMP Stack Blog

Node Project 1: fs.file

Note: You do not have to use Vim or Ubuntu to complete this project. Since I teach (and do) programming in an Ubuntu environment, I include Ubuntu/Vim commands and tips throughout my tutorials.

*****************
Language:
NodeJS (JavaScript)
*****************

*****************
Operating System:
Ubuntu (Linux)
*****************

*****************
Editor:
Vim
*****************

Vim is an editor commonly used on Unix Family Operating Systems. Linux is an Unix family OS.

Step 1: Make Directory

First, we will create a directory for our project. I am calling mine: myFiles

$ mkdir myFiles
$ cd myFiles
$ ls

mkdir - Make a directory called 'myFiles'
cd - Change directory to myFiles
ls - List what's in the directory. Right now it should be empty.

Step 2: Open Vim (Text Editor)

If you perfer another text editor, that's okay. I think it is good to get familar with Vim, because there are programming situations where no GUIs are available. Vim is just about always there on any UNIX family Operating System.

$ vim fileMaker.js

vim fileMaker.js - Will open a file called fileMaker.js, if it exists. In this case we are creating a new file called fileMaker and using vim to edit it.

Step 3: Write Code

vim command:
Press i to go to insert mode.

Use the tips in Vim Intro to enter the following code:

Learn Google Cloud

'use strict'; // prevents many common coding mistakes
var fs = require('fs'); // file system
var file = 'cherry.json'; // file name
var data = { name: 'Candy',  // JavaScript Object
             title: 'Commander'};

// JS Object -> JSON string
var fileData = JSON.stringify(data);

/* Asynchronous Function:
   create/rewrite a file */
  fs.writeFile(file, fileData, function (err) {
    if (err) throw err; // if error, return error
    else {
      console.log(file + ' Saved!'); // Print
    }
  });

  
  /* Asynchronous Function:
     read a file */
  fs.readFile(file,function (err, data) {
    if (err) throw err;  // if error, return error
    else {
      var object = JSON.parse(data); // file data -> JS object
      console.log(object); // print 
    }
  });
  

Step 4: Save and Quit

Command Mode

Type esc to go back to command mode

Save

Type :w! to save

Quit

Type: :q! to quit

Step 5: Run fileMaker.js

candy@cc:~/myFiles$ node fileMaker.js

When you run the code by typing the above command you should see:

candy@cc:~/myFiles$ node fileMaker.js
candy@cc:~/myFiles$ cherry.json Saved!
candy@cc:~/myFiles$ { name: 'Candy', title: 'Commander' }
Blockchain Council

Previous Lesson | Next Lesson