Search code examples
javascriptnode.jsfile-type

Node.js get file extension


Im creating a file upload function in node.js with express 3.

I would like to grab the file extension of the image. so i can rename the file and then append the file extension to it.

app.post('/upload', function(req, res, next) {
    var is = fs.createReadStream(req.files.upload.path),
        fileExt = '', // I want to get the extension of the image here
        os = fs.createWriteStream('public/images/users/' + req.session.adress + '.' + fileExt);
});

How can i get the extension of the image in node.js?


Solution

  • I believe you can do the following to get the extension of a file name.

    var path = require('path')
    
    path.extname('index.html')
    // returns
    '.html'
    

    If you would like to get all extensions in a file name (e.g. filename.css.gz => css.gz), try this:

    const ext = 'filename.css.gz'
      .split('.')
      .filter(Boolean) // removes empty extensions (e.g. `filename...txt`)
      .slice(1)
      .join('.')
    
    console.log(ext) // prints 'css.gz'