sync.js
This file
Path
lib/stdio/sync.js
67 lines · 1.9 KiB · JavaScript
Last changed by
Refactor `stdio` option logic (#639)ehmickybefore adoptiond6b4553
History of this fileTake it
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import {readFileSync, writeFileSync} from 'node:fs';import {isStream as isNodeStream} from 'is-stream';import {handleInput} from './handle.js';import {TYPE_TO_MESSAGE} from './type.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync modeexport const handleInputSync = options => { const stdioStreams = handleInput(addPropertiesSync, options); addInputOptionSync(stdioStreams, options); return stdioStreams;};
const forbiddenIfStreamSync = ({value, optionName}) => { if (isNodeStream(value)) { forbiddenIfSync({type: 'nodeStream', optionName}); }
return {};};
const forbiddenIfSync = ({type, optionName}) => { throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]} in sync mode.`);};
const addPropertiesSync = { input: { filePath: ({value}) => ({value: readFileSync(value), type: 'stringOrBuffer'}), webStream: forbiddenIfSync, nodeStream: forbiddenIfSync, iterable: forbiddenIfSync, native: forbiddenIfStreamSync, }, output: { webStream: forbiddenIfSync, nodeStream: forbiddenIfSync, iterable: forbiddenIfSync, native: forbiddenIfStreamSync, },};
const addInputOptionSync = (stdioStreams, options) => { const inputValue = stdioStreams.find(({type}) => type === 'stringOrBuffer')?.value; if (inputValue !== undefined) { options.input = inputValue; }};
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync modeexport const pipeOutputSync = (stdioStreams, result) => { if (result.output === null) { return; }
for (const stdioStream of stdioStreams) { pipeStdioOptionSync(result.output[stdioStream.index], stdioStream); }};
const pipeStdioOptionSync = (result, {type, value, direction}) => { if (result === null || direction === 'input') { return; }
if (type === 'filePath') { writeFileSync(value, result); }};