Skip to content

Commit 98a53e3

Browse files
authored
Merge pull request #948 from bids-standard/improved-utf-8-decoding
Improve UTF-8 support in browser environments
2 parents 6b2a4e2 + adc6256 commit 98a53e3

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

bids-validator/utils/files/readFile.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ const JSONFilePattern = /.json$/
88
const isJSONFile = file =>
99
JSONFilePattern.test(isNode ? file.name : file.relativePath)
1010

11+
// Work around JSDom not providing TextDecoder yet
12+
if (typeof TextDecoder === 'undefined') {
13+
const { TextDecoder } = require('util')
14+
global.TextDecoder = TextDecoder
15+
}
16+
1117
/**
1218
* checkEncoding
1319
* @param {object | File} file - nodeJS fs file or browser File
@@ -33,12 +39,12 @@ const checkEncoding = (file, data, cb) => {
3339
function readFile(file, annexed, dir) {
3440
return new Promise((resolve, reject) => {
3541
if (isNode) {
36-
testFile(file, annexed, dir, function(issue, stats, remoteBuffer) {
42+
testFile(file, annexed, dir, function (issue, stats, remoteBuffer) {
3743
if (issue) {
3844
return reject(issue)
3945
}
4046
if (!remoteBuffer) {
41-
fs.readFile(file.path, function(err, data) {
47+
fs.readFile(file.path, function (err, data) {
4248
if (err) {
4349
return reject(err)
4450
}
@@ -54,7 +60,7 @@ function readFile(file, annexed, dir) {
5460
})
5561
} else {
5662
const reader = new FileReader()
57-
reader.onloadend = function(e) {
63+
reader.onloadend = e => {
5864
if (e.target.readyState == FileReader.DONE) {
5965
if (!e.target.result) {
6066
return reject(new Issue({ code: 44, file: file }))
@@ -63,8 +69,7 @@ function readFile(file, annexed, dir) {
6369
checkEncoding(file, buffer, ({ isUtf8 }) => {
6470
if (!isUtf8) reject(new Issue({ code: 123, file }))
6571
})
66-
const utf8Data = String.fromCharCode.apply(null, buffer)
67-
return resolve(utf8Data)
72+
return resolve(new TextDecoder().decode(buffer))
6873
}
6974
}
7075
reader.readAsArrayBuffer(file)

0 commit comments

Comments
 (0)