I am trying to upload some files, through an HTML form, in my local drive, which I was able to complete successfully. However, when attempting to play the mp3 uploaded file, by accessing the url of the "mp3 player", the server redirects me to the uploading page and I can not understand why this happens. I am quite a begginer, when it comes to node.js and I do not really know that much about JavaScript, as I have little experience with it. You can check the code below:

var http = require('http'),
fs = require('fs'),
filePath = './test.mp3',
stat = fs.statSync(filePath);
var formidable = require('formidable');

http.createServer(function(request, response) {

  if(request.url == '/playUploadedFile') {
    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size,

  if (request.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(request, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = __dirname + '/' + files.filetoupload.name;
      filePath = newpath;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        response.write('File uploaded and moved!');
        //request.url = '/playUploadedFile';
  } else {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    response.write('<input type="file" name="filetoupload"><br>');
    response.write('<input type="submit">');
    return response.end();


1 Answers

Community On Best Solutions

In order to serve static file you have to declare your upload path to static. This way node understands the files within the specified path needs to be served exactly the way it is. The easiest way to do this is to use express https://expressjs.com/en/starter/static-files.html. But you can also use node-static https://www.npmjs.com/package/node-static package as well.