From a1acc9d1ccd0ace721dc08f5b6380cfbeed8de7d Mon Sep 17 00:00:00 2001 From: Kalle Date: Fri, 21 Jun 2019 05:56:05 +0300 Subject: [PATCH] Add out-of-the-box support for browser using Fetch API Signed-off-by: Kalle --- README.md | 4 +--- index.js | 13 ++++++++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 79f0e2d..7751eeb 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,6 @@ tmx.parseFile(filename, function(err, map) { The second example in that list uses `tmx.readFile(filename, callback)` and then calls `tmx.parse(...)` on the results. -So if you're in browserland, you can replace the `readFile` function -with your own asset loading function. ## Documentation @@ -146,4 +144,4 @@ The `objects` array looks like this: TileLayer objects have a `tileAt(x, y)` method. Otherwise you can access `layer.tiles` in row-major order. -See the bottom of index.js for more information. +See the bottom of index.js for more information. \ No newline at end of file diff --git a/index.js b/index.js index a51b544..3265720 100644 --- a/index.js +++ b/index.js @@ -686,7 +686,18 @@ function parse(content, pathToFile, cb) { } function defaultReadFile(name, cb) { - fs.readFile(name, { encoding: 'utf8' }, cb); + var isBrowser = typeof window !== 'undefined'; + + if (isBrowser) { + fetch(name) + .then(response => response.text()) + .then(data => { + cb(undefined, data); + }) + .catch(e => cb(e)); + } else { + fs.readFile(name, { encoding: 'utf8' }, cb); + } } function parseFile(name, cb) {