json | select json | Cell 2 | Search

This code tests the selectJson function by reading a package.json file, simulating a slow data stream, and extracting the "dependencies" section from the JSON data. It demonstrates how to use selectJson with a stream input and logs the result.

Run example

npm run import -- "test stream by creating a slow stream"

test stream by creating a slow stream

var fs = require('fs')
var path = require('path')
var {Readable} = require('stream')
var importer = require('../Core')
var {selectJson} = importer.import("select json")

function testSelectJson() {
    var package = fs.createReadStream(
        path.join(__dirname, '../package.json'), {
            highWaterMark: 8
        })
    var slowStream = new Readable()
    slowStream._read = () => {}
    var delay = 50
    package.on('data', (data) => {
        delay += 50
        setTimeout(() => slowStream.push(data), delay)
    })
    return selectJson('//depenedencies', slowStream)
}

module.exports = testSelectJson

if(typeof $ !== 'undefined') {
    console.log(testSelectJson())
}

What the code could have been:

const fs = require('fs');
const path = require('path');
const { Readable } = require('stream');
const { importer } = require('../Core');
const { selectJson } = importer.import('select-json');

/**
 * Tests the selectJson function with a slow stream.
 * 
 * This function reads a package.json file and pushes its data to a slow stream.
 * The selectJson function is then used to extract the dependencies from the package.json.
 * 
 * @returns {Promise} A promise that resolves to the extracted dependencies.
 */
async function testSelectJson() {
  // Read the package.json file as a stream.
  const packageStream = fs.createReadStream(
    path.join(__dirname, '../package.json'),
    { highWaterMark: 8 }
  );

  // Create a slow stream that pushes data with a delay.
  const slowStream = new Readable();
  slowStream._read = () => {};

  // Delay the pushing of data by 50ms initially.
  let delay = 50;

  // Push the data from the package stream to the slow stream with a delay.
  packageStream.on('data', (data) => {
    delay += 50;
    setTimeout(() => slowStream.push(data), delay);
  });

  // Use the selectJson function to extract the dependencies from the package.json.
  return await selectJson('//dependencies', slowStream);
}

module.exports = testSelectJson;

// Check if $ is defined and log the result if it is.
if (typeof $!== 'undefined') {
  console.log(await testSelectJson());
}

This code defines a test function testSelectJson that demonstrates the usage of the selectJson function from the importer library.

Here's a breakdown:

In essence, this code tests the selectJson function by reading a package.json file, simulating a slow data stream, and selecting the "dependencies" section from the JSON data.