@stencila/jesta
Version:
Stencila plugin for executable documents using JavaScript
86 lines (85 loc) • 2.45 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeFile = exports.writeStdio = exports.writeString = exports.write = exports.schema = void 0;
const fs_1 = __importDefault(require("fs"));
const util_1 = require("util");
const errors_1 = require("./util/errors");
exports.schema = {
title: 'write',
description: 'Write content to a URL.',
required: ['content', 'output'],
properties: {
content: {
description: 'The content to write',
type: 'string',
},
output: {
description: 'The URL to write the content to.',
type: 'string',
pattern: '^(file|stdio|stdout|string)://.*',
},
},
};
/**
* Write content to a URL.
*
* @param content The content to write
* @param output The URL to write to
* @returns The URL that was written to (including the `content` for `file://` URLs)
*/
async function write(content, output) {
const match = /^([a-z]{2,6}):\/\//.exec(output);
if (match) {
const protocol = match[1];
switch (protocol) {
case 'string':
return writeString(content);
case 'stdio':
case 'stdout':
writeStdio(content);
break;
case 'file':
await writeFile(content, output.slice(7));
break;
default:
throw new errors_1.CapabilityError(`write over protocol "${protocol}"`);
}
}
else {
await writeFile(content, output);
}
return output;
}
exports.write = write;
write.schema = exports.schema;
/**
* Write content to a string URL
*
* @param content The content to write
*/
function writeString(content) {
return `string://${content}`;
}
exports.writeString = writeString;
/**
* Write content to standard output
*
* @param content The content to write
*/
function writeStdio(content) {
process.stdout.write(content);
}
exports.writeStdio = writeStdio;
/**
* Write content to the local file system
*
* @param content The content to write
* @param path The path of the file to write
*/
async function writeFile(content, path) {
return util_1.promisify(fs_1.default.writeFile)(path, content);
}
exports.writeFile = writeFile;