node/src/json_parser.h
Joyee Cheung ce8f085d26
sea: support embedding assets
With this patch:

Users can now include assets by adding a key-path dictionary
to the configuration as the `assets` field. At build time, Node.js
would read the assets from the specified paths and bundle them into
the preparation blob. In the generated executable, users can retrieve
the assets using the `sea.getAsset()` and `sea.getAssetAsBlob()` API.

```json
{
  "main": "/path/to/bundled/script.js",
  "output": "/path/to/write/the/generated/blob.blob",
  "assets": {
    "a.jpg": "/path/to/a.jpg",
    "b.txt": "/path/to/b.txt"
  }
}
```

The single-executable application can access the assets as follows:

```cjs
const { getAsset } = require('node:sea');
// Returns a copy of the data in an ArrayBuffer
const image = getAsset('a.jpg');
// Returns a string decoded from the asset as UTF8.
const text = getAsset('b.txt', 'utf8');
// Returns a Blob containing the asset.
const blob = getAssetAsBlob('a.jpg');
```

Drive-by: update the  documentation to include a section dedicated
to the injected main script and refer to it as "injected main
script" instead of "injected module" because it's a script, not
a module.

PR-URL: https://github.com/nodejs/node/pull/50960
Refs: https://github.com/nodejs/single-executable/issues/68
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
2024-02-02 15:25:34 +01:00

41 lines
1.2 KiB
C++

#ifndef SRC_JSON_PARSER_H_
#define SRC_JSON_PARSER_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include "util.h"
#include "v8.h"
namespace node {
// This is intended to be used to get some top-level fields out of a JSON
// without having to spin up a full Node.js environment that unnecessarily
// complicates things.
class JSONParser {
public:
using StringDict = std::unordered_map<std::string, std::string>;
JSONParser();
~JSONParser() = default;
bool Parse(const std::string& content);
std::optional<std::string> GetTopLevelStringField(std::string_view field);
std::optional<bool> GetTopLevelBoolField(std::string_view field);
std::optional<StringDict> GetTopLevelStringDict(std::string_view field);
private:
// We might want a lighter-weight JSON parser for this use case. But for now
// using V8 is good enough.
RAIIIsolateWithoutEntering isolate_;
v8::Global<v8::Context> context_;
v8::Global<v8::Object> content_;
bool parsed_ = false;
};
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_JSON_PARSER_H_