文章

Jekyll踩坑记录

1. MAC下用中文目录会报错

报错信息:

1
2
3
[2024-03-16T17:12:14.604920 #48807] ERROR -- : Exception rescued in listen-worker_thread:
Encoding::CompatibilityError: incompatible character encodings: ASCII-8BIT and UTF-8
/Users/mosaic/.rubies/ruby-3.1.3/lib/ruby/3.1.0/pathname.rb:450:in `join'

报错说的很明白,pathname.rb第450行的join方法报错了,具体报错信息是ASCII-8BIT和UTF-8两个字符集不兼容,去看看450行到底发生了什么

1
2
3
4
5
6
7
8
9
10
11
12
13
def children(with_directory=true)
    with_directory = false if @path == '.'
    result = []
    Dir.foreach(@path) {|e|
      next if e == '.' || e == '..'
      if with_directory
        result << self.class.new(File.join(@path, e)) # 第450行
      else
        result << self.class.new(e)
      end
    }
    result
  end

看起来是用json方法拼接字符串的时候,@path是ASCII-8BIT字符,e是UTF-8字符,所以报错了

我们平常肯定是用UTF-8的,那就把前面的@path转码为UTF-8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def children(with_directory=true)
    with_directory = false if @path == '.'
    result = []
    Dir.foreach(@path) {|e|
      next if e == '.' || e == '..'
      if with_directory
        #print e, "\n"
        #print @path, "\n"
        result << self.class.new(File.join(@path.force_encoding("UTF-8"), e))
      else
        result << self.class.new(e)
      end
    }
    result
  end
本文由作者按照 CC BY 4.0 进行授权