我用express 3在node.js中创建了一个文件上传函数。

我想抓取图像的文件扩展名。所以我可以重命名文件,然后附加文件扩展名。

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);
});

如何在node.js中获得图像的扩展名?


当前回答

扩展String.prototype的一行代码:

Object.defineProperty(String.prototype, "ext", {get: function(x) {return this.split('.').pop()}})
str = 'fox.fbx';
str.ext

结果:

其他回答

扩展String.prototype的一行代码:

Object.defineProperty(String.prototype, "ext", {get: function(x) {return this.split('.').pop()}})
str = 'fox.fbx';
str.ext

结果:

一个简单的解决方案,不需要require,解决了多个周期的扩展问题:

var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')); 
//ext = '.with.long.extension'

或者如果你不想要前导点:

var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')+1); 
//ext = 'with.long.extension'

确保测试文件也有扩展名。

使用substr()方法比使用split() & pop()方法更有效

在这里看看性能差异:http://jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substr(1);

Update August 2019 As pointed out by @xentek in the comments; substr() is now considered a legacy function (MDN documentation). You can use substring() instead. The difference between substr() and substring() is that the second argument of substr() is the maximum length to return while the second argument of substring() is the index to stop at (without including that character). Also, substr() accepts negative start positions to be used as an offset from the end of the string while substring() does not.

// you can send full url here
function getExtension(filename) {
    return filename.split('.').pop();
}

如果您正在使用express,请在配置中间件时添加以下行(bodyParser)

app.use(express.bodyParser({ keepExtensions: true}));

例如,您可以使用path.parse(path)

const path = require('path');
const { ext } = path.parse('/home/user/dir/file.txt');