Search code examples
javascriptjquerynode.jsfile-copying

File copying using NodeJS


I am trying to copy a file from one location to another location. Here is my code below and I am calling this script like [1] http://localhost:8000/prdcopy/acbd.pdf

var http = require('http');
var fs = require('fs');
var express=require('express');
var app=express();
var path_upload = "/234.567.890.123/";
var path_prodn  = "//123.345.678.999/sample/temp/";
    app.get('/prdcopy/:file',function(req,res){
    var rstream = fs.createReadStream(path_upload + req.params.file);
    var wstream = fs.createWriteStream(path_prodn + req.params.file);
    rstream.pipe(wstream);
    res.end();
    rstream.on('end', function () {
        console.log('SrcFile');
    });
    wstream.on('close', function () {
        console.log('Done!');
    });
});
var server=app.listen(8000,function(){
    console.log("listening on port 8000...");
});

It copies the file properly however after copying the Firefox browser opens up a PDF reader. There is no file loaded in it though. This is my first node script and I would like to know what is that I am doing wrong. In IE it is not opening any PDF Reader window.


Solution

  • This is not necessarily an error.
    With res.end() you are sending back an http response with no Content-Type header. What Firefox does in this case is detecting the .pdf at the end of the typed URL and assuming that the response will contain something that is displayable by the PDF viewer. This is not the case as you are not sending anything back (no body).

    Try substituting res.end() with something like:

    res.header("Content-Type", "text/html");
    res.end();
    

    You will see that no PDF viewever is displayed even in Firefox. You could also use other res methods that automatically set the content type for you. For instance, to send a json response back substitute res.end() with:

    status = {};
    status.message = "Copied successfully";
    res.json(status);