onnxruntime/js/web/test/test-shared.ts
Yulong Wang b8917ad84f
[js/web] fix nodejs detection (#16400)
### Description
We used to use `typeof fetch === 'undefined'` as condition to detect the
environment is Node.js or not. Before Node.js v18, this works. However,
in Node.js v18, it introduced `fetch` function, so this check does not
work any more.

This PR changes the condition to check whether `process`,
`process.versions` and `process.versions.node` exists.

Checking whether `process` exists is not enough. This is because in some
configuration, webpack may polyfill nodejs's process.
2023-06-20 00:20:58 -07:00

48 lines
1.4 KiB
TypeScript

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as base64 from 'base64-js';
import * as fs from 'fs';
import {promisify} from 'util';
import {Attribute} from '../lib/onnxjs/attribute';
import {Graph} from '../lib/onnxjs/graph';
export function base64toBuffer(data: string): Uint8Array {
return base64.toByteArray(data);
}
export function bufferToBase64(buffer: Uint8Array): string {
return base64.fromByteArray(buffer);
}
export async function readFile(file: string) {
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
// node
return promisify(fs.readFile)(file);
} else {
// browser
const response = await fetch(file);
return new Uint8Array(await response.arrayBuffer());
}
}
export async function readJsonFile(file: string): Promise<any> {
const content = await readFile(file);
return JSON.parse(new TextDecoder().decode(content));
}
/**
* create a single-node graph for unit test purpose
*/
export function createMockGraph(opType: string, attributes: Attribute): Graph {
const node: Graph.Node = {name: '', opType, inputs: [], outputs: [], attributes};
return {
getInputIndices: () => [],
getInputNames: () => [],
getOutputIndices: () => [],
getOutputNames: () => [],
getNodes: () => [node],
getValues: () => []
};
}