首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >节点强大的slugify文件名

节点强大的slugify文件名
EN

Stack Overflow用户
提问于 2014-06-14 23:09:18
回答 1查看 469关注 0票数 1

我一直在使用node-formidable对文件名做冗长的处理。我尝试过form.on,但它已经返回了不受欢迎的�替换字符。所以文件名'ěščř.png‘变成了'����.png’而不是escr.png

代码语言:javascript
复制
form.on('end', function(fields, files) {
    var new_location = 's:/localhost/nodejs/';      
    for(var i = 0; i < this.openedFiles.length; i++){
        var temp_path = this.openedFiles[i].path;
        var file_name = slug(this.openedFiles[i].name);
        fs.copy(temp_path, new_location + file_name, function(err) {  
                    if (err) {
                        console.error(err);}
                    else {
                            console.log("success!")
                    }
                });
    }     
});
EN

回答 1

Stack Overflow用户

发布于 2018-12-13 23:15:09

您没有为“slug”函数提供代码,所以我提供了新的slugify函数。'openedFiles‘也没有在你的代码中给出,我假设所有其他的东西都没问题。

在你核心需求的顶端

const path = require('path');使用此代码

代码语言:javascript
复制
form.on('end', function(fields, files) {
    var new_location = 's:/localhost/nodejs/';      
    for(var i = 0; i < this.openedFiles.length; i++){
        var temp_path = this.openedFiles[i].path;

        var baseName = path.basename(this.openedFiles[i].name);
        var extName = path.extname(this.openedFiles[i].name);
        var file_name = slugify(baseName) + '.' + extName;
        fs.copy(temp_path, new_location + file_name, function(err) {  
            if (err) {
                console.error(err);}
            else {
                    console.log("success!")
            }
        });
    }     
});

function slugify(text){
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24221280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档