### Start the Web Application Source: https://github.com/adaltas/node-csv/blob/master/demo/webpack/README.md Launch the web application using npm or npx to serve the bundled files. ```bash npm run start ``` ```bash npx http-server ./dist -p 8080 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/adaltas/node-csv/blob/master/demo/webpack/README.md Clone the project repository and navigate to the webpack demo directory. ```bash git clone https://github.com/adaltas/node-csv.git csv cd csv/demo/webpack ``` -------------------------------- ### Build and Run Project with npm Source: https://github.com/adaltas/node-csv/blob/master/demo/webpack-ts/README.md Use these npm scripts to build the project's assets and then start the application. ```bash npm run build npm run start ``` -------------------------------- ### JavaScript CSV Transform Example Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/transform.html This example demonstrates transforming JSON data using the `transform` function from the node-csv library. It requires the `transform` function to be imported. The handler function is evaluated dynamically from a string. ```javascript import {transform} from '/lib/esm/transform/index.js'; const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([ { "year": "XXXX", "phone": "XXX XXXX" }, { "year": "YYYY", "phone": "YYY YYYY" } ], null, 2); const handlerEl = document.getElementById('handler'); handlerEl.innerHTML = [ 'function(record, params){\n', ' record.phone = params.country_code + " " + record.phone', ' return record;', '}' ].join('\n'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ params: { country_code: "+AA" } }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const transformCtx = {}; eval(`transformCtx.handler = ${handlerEl.value}`); const options = JSON.parse(optionsEl.value); transform(input, transformCtx.handler, options, (err, data) => { if(err){ return alert('Invalid CSV: '+err.message); } outputEl.innerHTML = JSON.stringify(data, null, 2); }); }; ``` -------------------------------- ### Initialize and Display CSV Transform Elements Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/transform.html Sets up the initial HTML content for the input JSON, transform handler, and options for the CSV transformation demo. This code populates the respective DOM elements with default or example values. ```javascript const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([{"year": "XXXX", "phone": "XXX XXXX"}, {"year": "YYYY", "phone": "YYY YYYY"}], null, 2); const handlerEl = document.getElementById('handler'); handlerEl.innerHTML = [ 'function(record, params){\n', ' record.phone = params.country_code + " " + record.phone', ' return record;', '}' ].join('\n'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ params: { country_code: "+AA" } }, null, 2); const outputEl = document.getElementById('output'); ``` -------------------------------- ### Initialize JSON Input for CSV Transform Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/transform_sync.html Sets the initial JSON data to be transformed. This example provides a sample array of objects. ```javascript const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([{"year": "XXXX", "phone": "XXX XXXX"}, {"year": "YYYY", "phone": "YYY YYYY"}], null, 2); ``` -------------------------------- ### Streaming CSV Processing Pipeline Source: https://github.com/adaltas/node-csv/blob/master/packages/csv/README.md This example demonstrates a streaming CSV processing pipeline using the Node.js Stream API. It's suitable for large datasets where memory efficiency is crucial. Ensure the 'csv' package is imported. ```javascript // Import the package import * as csv from "csv"; // Run the pipeline csv // Generate 20 records .generate({ delimiter: "|", length: 20, }) // Transform CSV data into records .pipe( csv.parse({ delimiter: "|", }), ) // Transform each value into uppercase .pipe( csv.transform((record) => { return record.map((value) => { return value.toUpperCase(); }); }), ) // Convert objects into a stream .pipe( csv.stringify({ quoted: true, }), ) // Print the CSV stream to stdout .pipe(process.stdout); ``` -------------------------------- ### JavaScript CSV Transform Example Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/transform_sync.html This script demonstrates how to use the `transform` function from the node-csv library to manipulate JSON data. It includes setting up input JSON, a transformation handler function, and options, then executing the transform and displaying the output. Ensure the `transform` function is imported correctly. ```javascript import {transform} from '/lib/esm/transform/sync.js'; const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify(\[{ "year": "XXXX", "phone": "XXX XXXX" }, { "year": "YYYY", "phone": "YYY YYYY" }\], null, 2); const handlerEl = document.getElementById('handler'); handlerEl.innerHTML = \[ 'function(record, params){\n', ' record.phone = params.country_code + " " + record.phone\n', ' return record;\n', '}' \].join('\n'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ params: { country_code: "+AA" } }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const transformCtx = {}; eval(\`transformCtx.handler = ${handlerEl.value}\`); const options = JSON.parse(optionsEl.value); try{ const data = transform(input, transformCtx.handler, options); outputEl.innerHTML = JSON.stringify(data, null, 2); }catch(err){ alert('Invalid CSV: '+err.message); } }; ``` -------------------------------- ### Set CSV Transform Options Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/transform_sync.html Configures options for the CSV transformation, such as the country code to be used by the transform function. This example sets the country code to '+AA'. ```javascript const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ params: { country_code: "+AA" } }, null, 2); ``` -------------------------------- ### Initialize CSV Parse Demo Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/parse_sync.html Sets up the initial state for the CSV parsing demo, populating the input and options elements. ```javascript const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = [ 'year,phone', 'XXXX,XXX XXXX', 'YYYY,YYY YYYY' ].join('\n'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ columns: true }, null, 2); const outputEl = document.getElementById('output'); ``` -------------------------------- ### Initialize CSV Parsing with Options Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/parse.html Sets up the input CSV data, options, and output elements for the parsing demo. The `parse` function is called with the input string and options object. ```javascript import {parse} from '/lib/esm/parse/index.js'; const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = [ 'year,phone', 'XXXX,XXX XXXX', 'YYYY,YYY YYYY' ].join('\n'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ columns: true }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = inputEl.value; const options = JSON.parse(optionsEl.value); // Start parsing parse(input, options, function(err, data){ if(err){ return alert('Invalid CSV: '+err.message); } outputEl.innerHTML = JSON.stringify(data, null, 2); }); }; ``` -------------------------------- ### Test Project with npm Source: https://github.com/adaltas/node-csv/blob/master/demo/webpack-ts/README.md Execute the test script using npm. This primarily involves building the code with webpack. ```bash npm run test ``` -------------------------------- ### Initialize CSV Demo Script Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/csv_sync.html Sets up event listeners and initializes UI elements for the CSV demo. It parses JSON values from input fields to configure the CSV processing pipeline. ```javascript import * as csv from '/lib/esm/csv/sync.js'; const runEl = document.getElementById('run'); const generateOptionsEl = document.getElementById('generateOptions'); generateOptionsEl.innerHTML = JSON.stringify({ delimiter: '|', length: 10 }, null, 2); const parseOptionsEl = document.getElementById('parseOptions'); parseOptionsEl.innerHTML = JSON.stringify({ delimiter: '|' }, null, 2); const transformOptionsEl = document.getElementById('transformOptions'); transformOptionsEl.innerHTML = [ 'function(record){\n', ' return record;\n', '}' ].join('\n'); const stringifyOptionsEl = document.getElementById('stringifyOptions'); stringifyOptionsEl.innerHTML = JSON.stringify({ quoted: true }, null, 2); const outputEl = document.getElementById('output'); ``` -------------------------------- ### Initialize CSV Generator with Options Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/generate_sync.html Sets up event listeners and initializes the CSV generator with JSON options parsed from a textarea. The output is displayed as JSON. ```javascript const convertEl = document.getElementById('convert'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ "length": 10, "objectMode": true }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const options = JSON.parse(optionsEl.value); // Initialize the generator const records = csv_generate_sync.generate(options) outputEl.innerHTML = JSON.stringify(records, null, 2) }; ``` -------------------------------- ### Initialize and Convert JSON to CSV Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/stringify.html Sets up the HTML elements for input, options, and output, and defines the conversion logic. The conversion is triggered by a button click, parsing JSON input and options to generate CSV. ```javascript const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([{"year": "XXXX", "phone": "XXX XXXX"}, {"year": "YYYY", "phone": "YYY YYYY"}], null, 2); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({}, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const options = JSON.parse(optionsEl.value); // Start stringifying csv_stringify.stringify(input, options, function(err, data){ if(err){ return alert('Invalid CSV: '+err.message); } outputEl.innerHTML = JSON.stringify(data, null, 2); }) }; ``` -------------------------------- ### Bundle JavaScript Modules with Webpack Source: https://github.com/adaltas/node-csv/blob/master/demo/webpack/README.md Use npm or npx to build the JavaScript modules using the webpack configuration. ```bash npm run build ``` ```bash npx webpack --config webpack.config.js ``` -------------------------------- ### Initialize CSV Demo UI Elements Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/csv_sync.html Initializes the HTML elements for the CSV demo, setting default values for generation, parse, transform, and stringify options. This code is intended to be run in a browser environment. ```javascript const runEl = document.getElementById('run'); const generateOptionsEl = document.getElementById('generateOptions'); generateOptionsEl.innerHTML = JSON.stringify({ delimiter: '|', length: 10 }, null, 2); const parseOptionsEl = document.getElementById('parseOptions'); parseOptionsEl.innerHTML = JSON.stringify({ delimiter: '|' }, null, 2); const transformOptionsEl = document.getElementById('transformOptions'); transformOptionsEl.innerHTML = [ 'function(record){\n', ' return record;\n', '}' ].join('\n'); const stringifyOptionsEl = document.getElementById('stringifyOptions'); stringifyOptionsEl.innerHTML = JSON.stringify({ quoted: true }, null, 2); const outputEl = document.getElementById('output'); ``` -------------------------------- ### Generate CSV with JSON Options Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/generate_sync.html Use this JavaScript code to initialize the CSV generator with specified JSON options and display the output. Ensure the 'generate' function is imported from '/lib/esm/generate/sync.js'. ```javascript import {generate} from '/lib/esm/generate/sync.js'; const convertEl = document.getElementById('convert'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ "length": 10, "objectMode": true }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const options = JSON.parse(optionsEl.value); // Initialize the generator const records = generate(options) outputEl.innerHTML = JSON.stringify(records, null, 2) }; ``` -------------------------------- ### Sync API Record Transformation Source: https://github.com/adaltas/node-csv/blob/master/packages/stream-transform/README.md Illustrates transforming records using the synchronous API. Each record's first element is moved to the end. ```javascript import { transform } from "stream-transform/sync"; import assert from "assert"; const records = transform( [ ["a", "b", "c", "d"], ["1", "2", "3", "4"], ], function (record) { record.push(record.shift()); return record; }, ); assert.deepEqual(records, [ ["b", "c", "d", "a"], ["2", "3", "4", "1"], ]); ``` -------------------------------- ### Run CSV Pipeline Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/csv_sync.html Executes the CSV generation, parsing, transformation, and stringification pipeline when the 'run' button is clicked. It parses user-defined options from the UI, processes the data, and displays the output or any errors encountered. The transform handler is evaluated using eval. ```javascript runEl.onclick = (e) => { try{ const generateOptions = JSON.parse(generateOptionsEl.value); const parseOptions = JSON.parse(parseOptionsEl.value); const transform = {}; eval(`transform.handler = ${transformOptionsEl.value}`); const stringifyOptions = JSON.parse(stringifyOptionsEl.value); // Run the pipeline const input = csv_sync.generate(generateOptions); const rawRecords = csv_sync.parse(input, parseOptions); const refinedRecords = csv_sync.transform(rawRecords, transform.handler); const output = csv_sync.stringify(refinedRecords, stringifyOptions); outputEl.innerHTML = output; }catch(err){ outputEl.innerHTML = 'Error: ' + err.message; } }; ``` -------------------------------- ### Initialize and Generate CSV Data Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/generate.html This snippet initializes the CSV generator with specified JSON options and consumes the generated records using the readable stream API. It pushes each record to an array and updates the output element. Ensure the 'generate' function is imported correctly. ```javascript import {generate} from '/lib/esm/generate/index.js'; const convertEl = document.getElementById('convert'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ "length": 10, "objectMode": true, "sleep": 1000 }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const options = JSON.parse(optionsEl.value); const records = []; // Initialize the generator generate(options) // Use the readable stream api to consume generated records .on('readable', function(){ let record; while((record = this.read()) !== null){ records.push(record); outputEl.innerHTML = outputEl.innerHTML+'\n'+JSON.stringify(record) } }) // Catch any error .on('error', function(err){ console.error(err); }) // Test that the generated records matched the expected records .on('end', function(){ console.log(records) }); }; ``` -------------------------------- ### Execute CSV Transformation Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/transform_sync.html Handles the conversion process by parsing input JSON, evaluating the transform function, applying options, and displaying the transformed data. Includes basic error handling for invalid CSV input. ```javascript const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const transformCtx = {}; eval(`transformCtx.handler = ${handlerEl.value}`); const options = JSON.parse(optionsEl.value); try{ const data = stream_transform_sync.transform(input, transformCtx.handler, options); outputEl.innerHTML = JSON.stringify(data, null, 2); }catch(err){ return alert('Invalid CSV: '+err.message); } }; ``` -------------------------------- ### Run CSV Pipeline Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/csv_sync.html Executes the CSV processing pipeline when the 'run' button is clicked. It parses input options, generates CSV data, processes it through parsing, transformation, and stringifying steps, and displays the output or any errors encountered. ```javascript runEl.onclick = (e) => { try{ const generateOptions = JSON.parse(generateOptionsEl.value); const parseOptions = JSON.parse(parseOptionsEl.value); const transform = {}; eval(`transform.handler = ${transformOptionsEl.value}`); const stringifyOptions = JSON.parse(stringifyOptionsEl.value); // Run the pipeline const input = csv.generate(generateOptions); const rawRecords = csv.parse(input, parseOptions); const refinedRecords = csv.transform(rawRecords, transform.handler); const output = csv.stringify(refinedRecords, stringifyOptions); outputEl.innerHTML = output; }catch(err){ outputEl.innerHTML = 'Error: ' + err.message; } }; ``` -------------------------------- ### CSV Parsing with Options Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/parse_sync.html Use this code to parse CSV data synchronously with specified options. Ensure the 'parse' function is imported from '/lib/esm/parse/sync.js'. ```javascript import {parse} from '/lib/esm/parse/sync.js'; const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = [ 'year,phone', 'XXXX,XXX XXXX', 'YYYY,YYY YYYY' ].join('\n'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ columns: true }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = inputEl.value; const options = JSON.parse(optionsEl.value); // Start parsing try{ const data = parse(input, options); outputEl.innerHTML = JSON.stringify(data, null, 2); }catch(err){ return alert('Invalid CSV: '+err.message); } }; ``` -------------------------------- ### CSV Stringify Demo - JavaScript Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/stringify_sync.html This script handles the conversion of JSON input to CSV using csv-stringify. It parses JSON input and options, stringifies them to CSV, and displays the output. Includes basic error handling for invalid CSV. ```javascript const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([{"year": "XXXX", "phone": "XXX XXXX"}, {"year": "YYYY", "phone": "YYY YYYY"}], null, 2); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({}, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const options = JSON.parse(optionsEl.value); // Start stringifying try{ const data = csv_stringify_sync.stringify(input, options) outputEl.innerHTML = JSON.stringify(data, null, 2); }catch(err){ return alert('Invalid CSV: '+err.message); } }; ``` -------------------------------- ### Synchronous CSV Stringification Source: https://github.com/adaltas/node-csv/blob/master/packages/csv-stringify/README.md Illustrates the synchronous API for converting an array of arrays into a CSV string. Ensure the 'csv-stringify/sync' module is imported. ```javascript import { stringify } from "csv-stringify/sync"; import assert from "assert"; const output = stringify([ ["1", "2", "3", "4"], ["a", "b", "c", "d"], ]); assert.equal(output, "1,2,3,4\na,b,c,d\n"); ``` -------------------------------- ### Synchronous CSV Processing Pipeline Source: https://github.com/adaltas/node-csv/blob/master/packages/csv/README.md Use this synchronous pipeline for simple CSV operations. It requires importing the 'csv/sync' package. ```javascript import * as csv from "csv/sync"; // Run the pipeline import { generate, parse, transform, stringify } from "csv/sync"; // Run the pipeline const input = generate({ seed: 1, columns: 2, length: 2 }); const rawRecords = parse(input); const refinedRecords = transform(rawRecords, (data) => data.map((value) => value.toUpperCase()), ); const output = stringify(refinedRecords); // Print the final result console.log(output); //> OMH,ONKCHHJMJADOA //> D,GEACHIN ``` -------------------------------- ### Generate CSV with Options Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/generate.html Use this snippet to generate CSV records with specified options. It utilizes the readable stream API to process generated records and displays them in a textarea. Ensure the 'csv-generate' library is included. ```javascript const convertEl = document.getElementById('convert'); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({ "length": 10, "objectMode": true, "sleep": 1000 }, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const options = JSON.parse(optionsEl.value); const records = []; // Initialize the generator csv_generate.generate(options) // Use the readable stream api to consume generated records .on('readable', function(){ let record; while((record = this.read()) !== null){ records.push(record); outputEl.innerHTML = outputEl.innerHTML+'\n'+JSON.stringify(record) } }) // Catch any error .on('error', function(err){ console.error(err); }) // Test that the generated records matched the expected records .on('end', function(){ console.log(records) }); }; ``` -------------------------------- ### CSV Pipeline Demo Script Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/csv.html This script orchestrates a CSV processing pipeline, including generation, parsing, transformation, and stringification. It uses eval to dynamically set the transform handler. Ensure the transform handler is valid JavaScript. ```javascript import * as csv from '/lib/esm/csv/sync.js'; const runEl = document.getElementById('run'); const generateOptionsEl = document.getElementById('generateOptions'); generateOptionsEl.innerHTML = JSON.stringify({ delimiter: '|', length: 10 }, null, 2); const parseOptionsEl = document.getElementById('parseOptions'); parseOptionsEl.innerHTML = JSON.stringify({ delimiter: '|' }, null, 2); const transformOptionsEl = document.getElementById('transformOptions'); transformOptionsEl.innerHTML = [ 'function(record){\n', ' return record;\n', '}' ].join('\n'); const stringifyOptionsEl = document.getElementById('stringifyOptions'); stringifyOptionsEl.innerHTML = JSON.stringify({ quoted: true }, null, 2); const outputEl = document.getElementById('output'); runEl.onclick = (e) => { try{ const generateOptions = JSON.parse(generateOptionsEl.value); const parseOptions = JSON.parse(parseOptionsEl.value); const transform = {}; eval(`transform.handler = ${transformOptionsEl.value}`); const stringifyOptions = JSON.parse(stringifyOptionsEl.value); // Run the pipeline csv // Generate 20 records .generate(generateOptions) // Transform CSV data into records .pipe(csv.parse({ delimiter: '|' })) // Transform each value into uppercase .pipe(csv.transform(transform.handler)) // Convert objects into a stream .pipe(csv.stringify(stringifyOptions)) // Print the CSV stream to stdout .on('readable', function () { let chunck; while(chunck = this.read()){ outputEl.innerHTML = outputEl.innerHTML + chunck.toString() } }) .on('error', function (err) { outputEl.innerHTML = 'Error: ' + err.message; }); }catch(err){ outputEl.innerHTML = 'Error: ' + err.message; } }; ``` -------------------------------- ### tsconfig.json for CommonJS and Node16 Module Resolution (Initial) Source: https://github.com/adaltas/node-csv/blob/master/demo/ts-cjs-node16/README.md This `tsconfig.json` configuration was used to address the initial TypeScript import error. It sets `module` to `CommonJS` and `moduleResolution` to `node16`. ```json { "compilerOptions": { "esModuleInterop": true, "module": "CommonJS", "moduleResolution": "node16", "strict": true } } ``` -------------------------------- ### Handle CSV Conversion Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/parse_sync.html Attaches an event listener to the convert button to parse CSV input based on provided options and display the result as JSON. Includes basic error handling for invalid CSV. ```javascript convertEl.onclick = (e) => { const input = inputEl.value; const options = JSON.parse(optionsEl.value); // Start parsing try { const data = csv_parse_sync.parse(input, options); outputEl.innerHTML = JSON.stringify(data, null, 2); } catch (err) { return alert('Invalid CSV: ' + err.message); } }; ``` -------------------------------- ### CSV Pipeline Execution Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/csv.html Executes a CSV processing pipeline including generation, parsing, transformation, and stringification. Requires the 'csv' module to be imported. Handles potential errors during execution. ```javascript const runEl = document.getElementById('run'); const generateOptionsEl = document.getElementById('generateOptions'); generateOptionsEl.innerHTML = JSON.stringify({ delimiter: '|', length: 10 }, null, 2); const parseOptionsEl = document.getElementById('parseOptions'); parseOptionsEl.innerHTML = JSON.stringify({ delimiter: '|' }, null, 2); const transformOptionsEl = document.getElementById('transformOptions'); transformOptionsEl.innerHTML = [ 'function(record){ ', ' return record; ', '}' ].join('\n'); const stringifyOptionsEl = document.getElementById('stringifyOptions'); stringifyOptionsEl.innerHTML = JSON.stringify({ quoted: true }, null, 2); const outputEl = document.getElementById('output'); runEl.onclick = (e) => { try{ const generateOptions = JSON.parse(generateOptionsEl.value); const parseOptions = JSON.parse(parseOptionsEl.value); const transform = {}; eval(`transform.handler = ${transformOptionsEl.value}`); const stringifyOptions = JSON.parse(stringifyOptionsEl.value); // Run the pipeline csv // Generate 20 records .generate(generateOptions) // Transform CSV data into records .pipe(csv.parse(parseOptions)) // Transform each value into uppercase .pipe(csv.transform(transform.handler)) // Convert objects into a stream .pipe(csv.stringify(stringifyOptions)) // Print the CSV stream to stdout .on('readable', function () { let chunck; while(chunck = this.read()){ outputEl.innerHTML = outputEl.innerHTML + chunck.toString() } }) .on('error', function (err) { outputEl.innerHTML = 'Error: ' + err.message; }); }catch(err){ outputEl.innerHTML = 'Error: ' + err.message; } }; ``` -------------------------------- ### Execute CSV Transformation on Button Click Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/transform.html Attaches an event listener to the 'convert' button. When clicked, it parses the input JSON, evaluates the transform handler function, parses the options, and then uses the `stream_transform.transform` method to process the data. Errors are alerted, and the transformed data is displayed. ```javascript convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const transformCtx = {}; eval(`transformCtx.handler = ${handlerEl.value}`); const options = JSON.parse(optionsEl.value); stream_transform.transform(input, transformCtx.handler, options, (err, data) => { if(err){ return alert('Invalid CSV: '+err.message); } outputEl.innerHTML = JSON.stringify(data, null, 2); }); }; ``` -------------------------------- ### CSV Stringify with JSON Input Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/stringify.html Use this snippet to convert JSON data to CSV format. Ensure the input JSON is valid and provide any desired stringify options. ```javascript import {stringify} from '/lib/esm/stringify/index.js'; const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([{ "year": "XXXX", "phone": "XXX XXXX" }, { "year": "YYYY", "phone": "YYY YYYY" }], null, 2); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({}, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const options = JSON.parse(optionsEl.value); // Start stringifying stringify(input, options, function(err, data){ if(err){ return alert('Invalid CSV: '+err.message); } outputEl.innerHTML = JSON.stringify(data, null, 2); }) }; ``` -------------------------------- ### CSV Stringify with JSON Input Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/esm/stringify_sync.html Use this snippet to convert JSON data to CSV format. Ensure the input is valid JSON and provide an options object for customization. The output is displayed as a JSON string representing the CSV data. ```javascript import {stringify} from '/lib/esm/stringify/sync.js'; const convertEl = document.getElementById('convert'); const inputEl = document.getElementById('input'); inputEl.innerHTML = JSON.stringify([{ "year": "XXXX", "phone": "XXX XXXX" }, { "year": "YYYY", "phone": "YYY YYYY" }], null, 2); const optionsEl = document.getElementById('options'); optionsEl.innerHTML = JSON.stringify({}, null, 2); const outputEl = document.getElementById('output'); convertEl.onclick = (e) => { const input = JSON.parse(inputEl.value); const options = JSON.parse(optionsEl.value); // Start stringifying try{ const data = stringify(input, options) outputEl.innerHTML = JSON.stringify(data, null, 2); }catch(err){ return alert('Invalid CSV: '+err.message); } }; ``` -------------------------------- ### Stream API Usage for CSV Generation Source: https://github.com/adaltas/node-csv/blob/master/packages/csv-generate/README.md Illustrates the stream API for generating CSV records. Initialize the generator with options like seed, objectMode, columns, and length. Consume generated records using the readable stream API and handle errors. The 'end' event can be used to test the generated records against expected values. ```javascript import { generate } from "csv-generate"; import assert from "assert"; const records = []; // Initialize the generator generate({ seed: 1, objectMode: true, columns: 2, length: 2, }) // Use the readable stream api to consume generated records .on("readable", function () { let record; while ((record = this.read()) !== null) { records.push(record); } }) // Catch any error .on("error", function (err) { console.error(err); }) // Test that the generated records matched the expected records .on("end", function () { assert.deepEqual(records, [ ["OMH", "ONKCHhJmjadoA"], ["D", "GeACHiN"], ]); }); ``` -------------------------------- ### Handle CSV Conversion Event Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/parse.html Attaches an event listener to the convert button to parse CSV data from the input field using the specified options and display the result. ```javascript convertEl.onclick = (e) => { const input = inputEl.value; const options = JSON.parse(optionsEl.value); // Start parsing csv_parse.parse(input, options, function(err, data){ if(err){ return alert('Invalid CSV: '+err.message); } outputEl.innerHTML = JSON.stringify(data, null, 2); }); }; ``` -------------------------------- ### tsconfig.json for Node16 Module Resolution (Corrected) Source: https://github.com/adaltas/node-csv/blob/master/demo/ts-cjs-node16/README.md This corrected `tsconfig.json` configuration resolves the `TS5110` error by setting both `module` and `moduleResolution` to `node16`. This is required for compatibility when using `node16` module resolution. ```json { "compilerOptions": { "esModuleInterop": true, "module": "node16", "moduleResolution": "node16", "strict": true } } ``` -------------------------------- ### Parse CSV Data using Stream API Source: https://github.com/adaltas/node-csv/blob/master/packages/csv-parse/README.md Illustrates how to use the stream API of csv-parse to process CSV data. It configures a custom delimiter and handles records as they are parsed, including error handling and final assertion. ```javascript import assert from "assert"; import { parse } from "csv-parse"; const records = []; // Initialize the parser const parser = parse({ delimiter: ":", }); // Use the readable stream api to consume records parser.on("readable", function () { let record; while ((record = parser.read()) !== null) { records.push(record); } }); // Catch any error parser.on("error", function (err) { console.error(err.message); }); // Test that the parsed records matched the expected records parser.on("end", function () { assert.deepStrictEqual(records, [ ["root", "x", "0", "0", "root", "/root", "/bin/bash"], ["someone", "x", "1022", "1022", "", "/home/someone", "/bin/bash"], ]); }); // Write data to the stream parser.write("root:x:0:0:root:/root:/bin/bash\n"); parser.write("someone:x:1022:1022::/home/someone:/bin/bash\n"); // Close the readable stream parser.end(); ``` -------------------------------- ### TypeScript Import Error with CommonJS Source: https://github.com/adaltas/node-csv/blob/master/demo/ts-cjs-node16/README.md This error occurs when TypeScript cannot import a CommonJS module synchronously. It suggests using dynamic imports as a workaround. ```bash $ tsc main.ts:1:23 - error TS1471: Module 'csv-parse' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead. 1 import { parse } from 'csv-parse'; ~~~~~~~~~~~ Found 1 error in main.ts:1 ``` -------------------------------- ### TypeScript Compilation Error with Node16 Module Resolution Source: https://github.com/adaltas/node-csv/blob/master/demo/ts-cjs-node16/README.md This error arises after upgrading TypeScript when `module` is set to `CommonJS` while `moduleResolution` is `Node16`. The `module` option must match `moduleResolution` in this configuration. ```bash $ yarn test yarn run v1.22.19 $ tsc --noEmit tsconfig.json:4:15 - error TS5110: Option 'module' must be set to 'Node16' when option 'moduleResolution' is set to 'Node16'. 4 "module": "CommonJS", ~~~~~~~~~~ Found 1 error in tsconfig.json:4 error Command failed with exit code 2. ``` -------------------------------- ### Define CSV Transform Function Source: https://github.com/adaltas/node-csv/blob/master/demo/browser/iife/transform_sync.html Defines the JavaScript function used to transform each record in the CSV data. This function modifies the 'phone' field by prepending a country code. ```javascript const handlerEl = document.getElementById('handler'); handlerEl.innerHTML = [ 'function(record, params){', ' record.phone = params.country_code + " " + record.phone', ' return record;', '}' ].join('\n'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.