How to Upload File in Node.js

In this article we will have a look at uploading a file on a web server created using Node.js.

In this article we will have a look at uploading a file on a web server created using Node.js. Stream in Node.js makes this task super easy to upload files or for that matter working with any data transfer between a server and a client.
 
To upload a file we will work with two modules, HTTP and fs. So let us start with loading these two modules in an application:

var http = require('http');
var fs = require('fs');

Once modules are loaded proceed to and create a web server as in the following:

 http.createServer(function(request,response){    
  }).listen(8080);

So far we are good and now we wish to use the following procedure:

  1. Create a destination write stream. In this stream the content of the uploaded file will be written.
  2. We want to write back to the client the percentage of data being uploaded.

The first requirement can be done using a pipe. A pipe is an event of stream in Node.js. And the request is a readable stream. So we will use a pipe event to write a request to a readable stream.

var destinationFile = fs.createWriteStream("destination.md");      
      request.pipe(destinationFile); 

 
The second requirement is to return a of data uploaded. To do that first read the total size of the file being uploaded. That can be done by reading the content-length (line number 1 in the following code snippet).  Then in the data event of the request we will update uploadedBytes that begins at zero (line number 2). In the data event of the request we are calculating the percentage and writing it back in the response.

var fileSize = request.headers['content-length'];
      var uploadedBytes = 0 ;
      request.on('data',function(d){                              
          uploadedBytes += d.length;
          var p = (uploadedBytes/fileSize) * 100;
          response.write("Uploading " + parseInt(p)+ " %\n");
     });

Putting it all together your app should contain the following code to upload a file and return the percentage uploaded.
 
var http = require('http');
var fs = require('fs');

  http.createServer(function(request,response){    
    response.writeHead(200);
      var destinationFile = fs.createWriteStream("destination.md");      
      request.pipe(destinationFile);

      var fileSize = request.headers['content-length'];
      var uploadedBytes = 0 ;

      request.on('data',function(d){  
                            
          uploadedBytes += d.length;
          var p = (uploadedBytes/fileSize) * 100;
          response.write("Uploading " + parseInt(p)+ " %\n");

     });

      request.on('end',function(){
            response.end("File Upload Complete");
          });

    }).listen(8080,function(){        
        console.log("server started");
        
        });


On a command prompt start the server as in the following:

command prompt start server
 
Now let us use curl -upload-file to upload a file on the server.

upload a file on server

As you see, while the file is being uploaded the percentage of data uploaded is returned back to the client. So in this way you can upload a file to the server created using Node.js. I hope you find this article useful. Thanks for reading.