In the last couple of posts we have seen on how we can get started with NodeJS and create a server that would serve the purpose of interacting with various clients. In this post we will be looking at how we can do file operations with NodeJS.
The most basic operations that a server script should be well versed in doing is the file manipulation. File manipulation mainly includes reading and writing files. With NodeJS however, these operations are mere simple.
Reading From File
Before we do anything, let’s create a server and host it at port 8880. The following code would do that for us.
1: var http = require('http');
2:
3: var onServerRequested = function(request, response){
4:
5: }
6:
7: http.createServer(onServerRequested).listen(8880);
8:
9: console.log('server is listening on 8880..');
Now what we need to do is this, whenever the request is made to the server, we read a file ‘simple.txt’ and send it’s content right back to the client.
In order to do file operations, we need to include one more module, filesystem, ‘fs’. So on including ‘fs’ module and making a read request to the file ‘simple.txt’ would result in following code.
1: var http = require('http');
2: var fs = require('fs');
3:
4: var onServerRequested = function(request, response){
5:
6: fs.readFile('simple.txt',function(err, content){
7: response.writeHead(200);
8: response.end(content);
9: });
10: }
11:
12: http.createServer(onServerRequested).listen(8880);
13:
14: console.log('server is listening on 8880..');
The readFile method reads the specified file and on completed reading the file (no matter whether the readFile was a success or not) it will execute the callback method and it goes like readFile(<fileName>,<callback>). In the callback function we return the content of the file in the response. If you run the server and access it via a web browser the output would be like:
Writing To The File
Another interesting aspect of NodeJS is writing content to the file. Let’s start with the same old structure where our server is listening at the port 8880. But instead of readFile method, this time, it would be writeFile. The code would be like:
1: var http = require('http');
2: var fs = require('fs');
3:
4: var onServerRequested = function(request, response){
5:
6: fs.writeFile('another.txt','Hello File content', function(err){
7: response.writeHead(200);
8: response.end();
9: });
10: }
11:
12: http.createServer(onServerRequested).listen(8880);
13:
14: console.log('server is listening on 8880..');
For writeFile, the method’s parameters are writeFile(<fileName>,<content to write>,<callback>). So what above code does is, as soon as it receives request, it creates a file another.txt and write ‘Hello file content’ to it. And when it completes the write to file operation, it ends the response.
So, we have seen how we can read and write files using NodeJS. I think the post was helpful. Stay tuned for more.
Happy Coding.
0 comments