Reading and Writing to File using Node

Working with File Paths


var path = require('path');


path.direname('dir1/dir2/dir3/fileName.txt');  // returns "/dir1/dir2/dir3"

path.basename('dir1/dir2/dir3/fileName.txt');  
// returns "fileName.txt"

path.basename('dir1/dir2/dir3/fileName.txt', '.txt');  
// returns "fileName"

path.etxname('dir1/dir2/dir3/fileName.txt');  
// returns ".txt"

path.existsSync('dir1/dir2/dir3/fileName.txt');
  // returns true / false

path.exists('dir1/dir2/dir3/fileName.txt', fuction(exists) {

//Do something here  (the .exists() function is a synchronous function which required a callback to be informed of the result once completed. If you would like to avoid using a callback, use the .existsSync() function as the previous example)

});

Using FileStream to Read a File


var fs = require('fs');

fs.open('myFolder/fileToOpen', 'r', function(err, fileDescription) {  //Do something with fileDescription } );

Note: the second argument of .open() is ‘r’ which is a command to open file. There are different commands, which are:

  • ‘r+’ opens file for reading and writing with the stream positioned at the beginning of the file (any new text is written at the beginning of the file)
  • ‘w’ creates a new file or deletes all content of the given file.
  • ‘w+’ creates a new file or deletes all content of the given file and opens the file for writing with the stream positioned at the beginning of the file (any new text is written at the beginning of the file)
  • ‘a’ open the file for writing, if it doesn’t exist it created it, and this time the stream is positioned at the end of the file (any new text is written at the current end of the file)
  • ‘a+’ open the file for reading and writing, if it doesn’t exist it created it, and this time the stream is positioned at the end of the file (any new text is written at the current end of the file)

Lets start by READING A FILE:

Create a new folder named “testingFileStreams” and create a new JavaScript file named “test.js” inside the new folder. In the same folder create a text file and add some random text (I have used Lopem Ipsum) and name it fileToRead.txt .

Open the test.js in edit mode and enter the following:

var fs = require('fs');
fs.open('fileToRead.txt', 'r', function opened(err, fileDescription){


if(err) { throw err }

var buffer = new Buffer(100), //Sets the butter to get the 100 bytes
bufferOffset = 0, //Start reading from position 0
bufferLength = buffer.length, //Reads the buffer bytes
filePosition = 0; //Reads from beginning of file

fs.read(fileDescription, buffer, bufferOffset, bufferLength, filePosition, function read(err, readBytes) {

if(err) { throw err }

console.log('Total Bytes: ' + readBytes);
if(readBytes > 0)
console.log(buffer.slice(0, readBytes));
});

});

The above code will open the file for reading using the .open() function and calling the function read() when the file has been opened. The first argument in the read() function, indicates any errors that might occur and we therefore we use if(err) { throw err } which cannot be avoided or the function will stop working if it encounters any error. The second argument in the read() function we created, is readBytes which represents the bytes read from the file. Here we are only displaying the total bytes read in file and printing the bytes if there are more than 0 bytes.

To test this function is working properly:

  • open the cmd (command-line)
  • change directory to the folder created.
  • Type “node test.js” to run the JavaScript on Node.

readFile

Note: to print the content in a string, you simply need to change the line console.log(buffer.slice(0, readBytes)); to console.log(buffer.slice(0, readBytes).toString());

And now, lets try WRITING TO A FILE:

Open the test.js in edit mode in a notepad or whatever you feel most comfortable with and add:

fs.open(‘fileToRead.txt’, ‘a’, function opened(err, fileDescription){

if(err) { throw err }

var buffer = new Buffer('Added: Rochelle added this sentence.'),
bufferPosition = 0,
bufferLength = buffer.length, //Bytes of the new buffer string
filePosition = null;

fs.write(fileDescription, buffer, bufferPosition, bufferLength, filePosition, function written(err, writtenBytes) {

if(err) { throw err }

console.log('Total Bytes Written to File: ' + writtenBytes);
});

});

The above code will open the file ‘fileToRead.txt’ for reading and writing with the stream positioned at the end of the file so that when we write, we append to the end of file rather to the beginning of the file. This function will open the file and add ‘Rochelle added this sentence’ in bytes to the end of file and save it. Once this is written, the total written bytes should be printed to screen.

To test this function is working properly:

  • go back to the cmd (command-line)
  • Type “node test.js” to run the JavaScript on Node again.
  • open the ‘fileToRead.txt’ in Notepad or any other text reader and you should see the newly added sentence.

writeFile

So that is how you open, read and write to files 🙂

Advertisements

Creating, Exporting and Loading Modules in Node

In this post we will cover the basics of what Modules are, how to create modules, export modules and require (reference) a module. If you are already aware of what Modules are, you can skip the first part and jump straight away to the hands on examples.

What are Modules?

One of the disadvantages of JavaScript is the global namespace sharing amongst different scrips. This is caused by the fact that when you load one or more JavaScript files/code, it is injected to one global namespace and thus if you had defined one global variable on one file, and the same in the other file, this will confict and create all sorts of bugs. This is where node helps in fixing this issue. Node used CommonJS to standardize packaging of JavaScript Libraries, called modules. Each module has its own context and does not conflict or interfere with other modules which eliminates the use of one global namespace by exposing a public API that can be used any time after importation.

A Module can be classified either as a Core Module, File Module, Folder Module or a third-party Module.

  • Core Modules expose some Node core functions that a programmer needs which are preloaed when a Node process starts. When referencing a Core Module, only the module name is used.
  • A file or folder module, are modules created by the programmer himself or others around him and are referenced by the file path or by file name. When referencing a module by file name, it will automatically map it into a file path, taking the assumption it is in the current file path.
  • A folder module can be referenced by the folder path without the filename and node will assume this folder is a package. Thus, node will look for a package definition in json format with the name package.json and if not found it sets the default file value of index.js.
  • Third-party Modules are modules available to download and install. Installing third-party modules is made easy through the NPM (Node Package Manager) and are referenced by module name.

Continue reading

Node JS hello World Quick Tutorial

Why use Node.js ?

If you have been working on the web for a while, you definitely had to use JavaScript at some point. Now, if you have been using JavaScript for the front-end, we need to switch to some other language when working on the backend. This switching might be tiring or confusing. Node is literally a server-side language using JavaScript. That means that both the front-end and the back-end can be created using JavaScript, eliminating the switching hassle.  So, especially if you enjoy working with JavaScript, Node is for you. Node has been built on JavaScript since it has closures and first-class functions which makes node allowing strong event-driven programming. In fact, Node is event-driven and thus the flow of execution is determined by the events handled by event handlers and callbacks allowing for asynchronous programming.

Installing Node.js

Visit the node.js website and click the “Download Button” under the big Install Button.

1.download

Depending on what type of Operating System you are using, select the appropriate type. In my case, I have a windows 64-bit, so I have downloaded the first (msi) download:

2.download-type

When download is complete, run the file and keep clicking “next” until installing starts. Click Finish when install is complete.

Testing Node

Lets just make sure Node is successfully installed.

To launch node – Open the cmd (command-line) and type:

node                                                       –             this is the command given to launch node. A new line should appear with the symbol “>” as shown below

3.node

To close node you will need to press “CTRL + C” and it will ask you to press “CTRL + C” again to exit. Once you press “CTRL + C” twice, node will exit.

4.node-quit

Running Hello World using Node

Now lets create a simple “Hello World” print using node. Open the cmd (command-line) and type:

mkdir HelloWorldFolder             –            this will create a new folder named “HelloWorldFolder”

cd HelloWorldFolder                     –            this will change directory and enter the new folder “HelloWorldFolder”

Now open the new created folder in windows form if you feel more comfortable and create a file name “test.js”

Open the new file using a simple text editor and paste only the following to display Hello World on-screen:

// Call the console.log function.
console.log(“Hello World”);

notepad

Back to command line to run the js file and type:

node test.js                                      –             this will run the file “test.js”  in node

As you can see below node is running the js file and printing “Hello World” on the screen.

5.run-node

Pretty quick and easy.. enjoy 😉