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.
Vim is an editor commonly used on Unix Family Operating Systems. Linux is an Unix family OS.
First, we will create a directory for our project. I am calling mine: myFiles
➼ mkdir
-
Make a directory called 'myFiles'
➼ cd
-
Change directory to myFiles
➼ ls
-
List what's in the directory. Right now it should be empty.
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
-
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.
Use the tips in Vim Intro to enter the following code:
'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
}
});
When you run the code by typing the above command you should see: