我用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中获得图像的扩展名?
使用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.
路径。Extname在大多数情况下都可以。但是,它将包括最后一个.之后的所有内容,包括http请求的查询字符串和散列片段:
var path = require('path')
var extname = path.extname('index.html?username=asdf')
// extname contains '.html?username=asdf'
在这种情况下,你可以尝试这样做:
var regex = /[#\\?]/g; // regex of illegal extension characters
var extname = path.extname('index.html?username=asdf');
var endOfExt = extname.search(regex);
if (endOfExt > -1) {
extname = extname.substring(0, endOfExt);
}
// extname contains '.html'
请注意,具有多个句点的扩展(例如.tar.gz)在path.extname下根本不起作用。