— Deno, CSV, File Handling, JavaScript, TypeScript — 1 min read
Deno, the secure runtime for JavaScript and TypeScript, continues to evolve with new features and improvements. Among its many functionalities, Deno provides a straightforward way to read CSV (Comma-Separated Values) files, a common data format used for storing tabular data.
Before we begin, ensure that you have Deno installed on your system. You can install Deno by following the instructions on the official Deno website.
Once Deno is installed, create a new TypeScript file for your Deno project. For this tutorial, let's name it read_csv.ts
.
Let's start with an example CSV file that we'll use for demonstration purposes. Below is a Markdown representation of the CSV file:
Name | Age | Gender | Occupation |
---|---|---|---|
John | 30 | Male | Software Eng |
Alice | 25 | Female | Data Scientist |
Bob | 35 | Male | Web Developer |
Emily | 28 | Female | UX Designer |
Save this table to a file named data.csv
in your project directory.
Deno provides various built-in modules and supports third-party modules from a variety of sources. In this example, we'll use jsr:@std/csv
to parse the CSV file:
1// Importing necessary modules2import { parse } from "jsr:@std/csv";3
4// Function to read CSV file5async function readCSV(filePath: string) {6 // Open the CSV file as text7 const data = await Deno.readTextFile(filePath);8
9 // Parse the CSV content10 const records = parse(data, {11 skipFirstRow: true, // Skip header row if present12 });13
14 // Return parsed CSV data15 return records;16}17
18// Usage example19const filePath = "data.csv";20const csvData = await readCSV(filePath);21console.log(csvData);
parse
function from the jsr:@std/csv
module. This module can parse CSV data.readCSV
function takes a file path as input, reads the CSV file as text using Deno.readTextFile
, and then parses the CSV content using the parse
function.data.csv
in this case) and call the readCSV
function to read the CSV file.Once the CSV data is parsed, you can manipulate it according to your requirements. For instance, you might want to perform data processing, filtering, or analysis.
Reading a CSV file with Deno is a straightforward process, especially with modules like jsr:@std/csv
. By following the steps outlined in this tutorial, you can efficiently read CSV files in your Deno projects and leverage the data for your own purposes!