- JavaScript — Parse CSV data into an array
- Parsing CSV string into an array
- Conclusion
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
- Javascript файл в массиве
- # Read a text file into an Array asynchronously in Node.js
- # Read a text file into an Array synchronously using Node.js
- # Read a text file into an Array asynchronously using .then()
- # Additional Resources
- Reading a text file into an Array in Node.js
- Example (Using readFileSync())
- Output
- Example (Using async readFile())
- Output
- Курсы javascript
JavaScript — Parse CSV data into an array
This tutorial will help you learn how to receive a CSV file using HTML element and parse the content as a JavaScript array.
To convert or parse CSV data into an array , you need to use JavaScript’s FileReader class, which contains a method called readAsText() that will read a CSV file data and parse the result as a string text.
The FileReader class is a web API, so this solution only works in the browser. If you need to parse CSV file from Node.js, see my JavaScript read CSV guide.
Once you have the string , you can create a custom function to turn the string into an array .
For example, a CSV file with the following content:
Will be converted into the following JavaScript array:
The code for this tutorial is shared here.
First, let’s see how to accept a CSV file from the browser using HTML elements.
You need to have an HTML form that accepts a CSV file using an element. Here’s a simple way to create one:
Now that you have the HTML elements ready, it’s time to write a script that will listen for the form’s submit event.
Just right under the tag, write a tag with the following content:
First, you need the e.preventDefault() code to prevent the browser’s default submit behavior, which will refresh the page. After that, you can write the code to execute when submit event is triggered by the user.
You need to take the uploaded CSV file using JavaScript like this:
Then, you need to create a new instance of FileReader class using the following code:
First, you need to define what happens when the reading operation has been completed with the onload event handler. The result of the reading operation is passed to the event.target.result property as follows:
Then you can instruct the reader to read a specific file as follows:
Now that you know how JavaScript FileReader works, let’s put the code together to read the uploaded CSV file. The full HTML page code will be as follows:
You can test the code using mock_data.csv file provided in the GitHub repo.
You will see the CSV content rendered on your browser. This means the has been able to read the CSV file content as a string without any problem. You just need to parse this string as an array of objects next.
Parsing CSV string into an array
To parse a CSV string into an array, you need to write a code that will separate the string between CSV headers and CSV rows. Then, you need to put each row as one object element, using the headers as the property names and the row as the values.
- A string of CSV content
- The delimiter (or separator) of the CSV content, usually a comma ,
Here’s the function syntax:
In this function, you need to create two arrays called headers and rows . The headers will contain the first row of the CSV file, while the rows will contain all the values, from the second row to the last.
This can be achieved by first slicing the string, then use the split() method to split a string into an array.
Once you have both the headers and the rows , it’s time to create the array of objects. First, you need to map the rows array and split() the values from each row into an array.
Then, you need to use the reduce() method on the headers array, returning an object with each header as the property name and the data from values at the same index as the property value.
Finally, you just need to return each mapped row as the array element. The full function code is as follows:
With that, your csvToArray() function is finished. You just need to call the function from the onload event:
You can view the full HTML code in the GitHub repo
Conclusion
You’ve just learned how to create a JavaScript array out of a CSV file uploaded through the HTML form. At other times, you may want to parse a CSV array fetched from an API or remote URL as an array.
Depending on the data returned from your request, you can either use the FileReader to read the CSV content as a string first, or you just need to parse the string as an array if you already receive a string from your API.
Also, pay attention to the delimiter of your CSV file. The csvToArray() function already has a sensible default delimiter which is a comma, but you may use other symbols. If that’s so, you can pass the right delimiter as the second argument to the function call.
Feel free to modify the code examples to fit your requirements 😉
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Javascript файл в массиве
Last updated: Mar 28, 2022
Reading time · 3 min
# Read a text file into an Array asynchronously in Node.js
To read a text file into an array:
- Use the fsPromises.readFile() method to read the file’s contents.
- Await the promise that the method returns.
- Use the String.split() method to split the string into an array of substrings.
Copied!// 👇️ if using ES6 Imports uncomment line below // import from 'fs'; const promises: fsPromises> = require('fs'); // ✅ read file ASYNCHRONOUSLY async function asyncReadFile(filename) try const contents = await fsPromises.readFile(filename, 'utf-8'); const arr = contents.split(/\r?\n/); console.log(arr); // 👉️ ['One', 'Two', 'Three', 'Four'] return arr; > catch (err) console.log(err); > > asyncReadFile('./example.txt');
The code snippet assumes that there is an example.txt file located in the same directory. Make sure to also open your terminal in that same directory.
Copied!One Two Three Four
The directory structure in the example assumes that the index.js file and the example.txt file are located in the same folder and our terminal is also in that folder.
The fsPromises.readFile() method asynchronously reads the contents of the provided file.
If you don’t provide a value for the encoding parameter, the method returns a buffer, otherwise, a string is returned.
The method returns a promise that resolves with the contents of the file, so we either have to await it or use the .then() method on it to get the resolved string.
We used the String.split() method to split the contents on each newline character.
We passed a regular expression to the split() method.
Copied!const arr = contents.split(/\r?\n/);
The forward slashes / / mark the beginning and end of the regular expression.
For example, Windows uses \r\n as an end-of-line character, whereas \n is the default in Unix.
The question mark ? matches the preceding item (\r) 0 or 1 times. In other words, the \r might or might not be there.
The split() method returns an array containing the substrings (each line) as elements.
Alternatively, you can read the file synchronously.
# Read a text file into an Array synchronously using Node.js
Use the fs.readFileSync method to read a text file into an array synchronously.
The method will return the contents of the file, which we can split on each newline character to get an array of strings.
Copied!// 👇️ if using ES6 Imports uncomment line below // import from 'fs'; const readFileSync> = require('fs'); // ✅ read file SYNCHRONOUSLY function syncReadFile(filename) const contents = readFileSync(filename, 'utf-8'); const arr = contents.split(/\r?\n/); console.log(arr); // 👉️ ['One', 'Two', 'Three', 'Four'] return arr; > syncReadFile('./example.txt');
The function from the first example reads the contents of a file synchronously.
The fs.readFileSync method takes the path to the file as the first parameter and the encoding as the second.
The method returns the contents of the provided path.
If you omit the encoding parameter, the function will return a buffer, otherwise, a string is returned.
# Read a text file into an Array asynchronously using .then()
The first code sample reads a text file into an array asynchronously using async/await .
If you prefer using the .then() and .catch() syntax when handling Promises, use the following code snippet instead.
Copied!// 👇️ if using ES6 Imports uncomment line below // import from 'fs'; const promises: fsPromises> = require('fs'); // ✅ read file ASYNCHRONOUSLY function asyncReadFile(filename) return fsPromises .readFile(filename, 'utf-8') .then(contents => const arr = contents.split(/\r?\n/); console.log(arr); // 👉️ ['One', 'Two', 'Three', 'Four'] return arr; >) .catch(err => console.log(err); >); > asyncReadFile('./example.txt');
The code sample achieves the same result but makes use of the .then() and .catch() syntax instead of a try/except block using async/await .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Reading a text file into an Array in Node.js
We can read a text file and return its content as an Array using node.js. We can use this array content to either process its lines or just for the sake of reading. We can use the ‘fs’ module to deal with the reading of file. The fs.readFile() and fs.readFileSync() methods are used for the reading files. We can also read large text files using this method.
Example (Using readFileSync())
Create a file with name – fileToArray.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
fileToArray.js
// Importing the fs module let fs = require("fs") // Intitializing the readFileLines with the file const readFileLines = filename => fs.readFileSync(filename) .toString('UTF8') .split('
'); // Calling the readFiles function with file name let arr = readFileLines('tutorialsPoint.txt'); // Printing the response array console.log(arr);
Output
C:\home
ode>> node fileToArray.js [ 'Welcome to TutorialsPoint !', 'SIMPLY LEARNING', '' ]
Example (Using async readFile())
Let’s take a look at one more example.
// Importing the fs module var fs = require("fs") // Intitializing the readFileLines with filename fs.readFile('tutorialsPoint.txt', function(err, data) < if(err) throw err; var array = data.toString().split("
"); for(i in array) < // Printing the response array console.log(array[i]); >>);
Output
C:\home
ode>> node fileToArray.js Welcome to TutorialsPoint ! SIMPLY LEARNING
Курсы javascript
Доброго времени суток.
Имею проблему: пишу обработку данных для специализированного софта (это ПО поддерживает автоматизацию через написание скриптов на JavaScript). Хочу прочитать данные из файла в массив. обращение к файлу происходит так:
var oDmFile = new ActiveXObject("DmFile.DmTableADO");
далее в цикле идёт считывание данных в массив из файла, представляющего собой таблицу во внутреннем формате ПО. причём, каждый элемент создаваемого массива — сам по себе массив. делаю следующее:
var Source=[];//рабочий массив - сюда должны писаться данные из файла var tmpArray=[0,0,0];//временный массив, нужен только для объяснения, что каждый член массива Source - массив oDmFile.Open("tmp1.dm", true);//открываю файл var num = oDmFile.GetRowCount();//определяю количество записей for (i=1;i<=num;i++) < Source[i]=tmpArray;//объясняю, что текущий элемент рабочего массва - массив Source[i][0]=oDmFile.GetNamedColumn(BodyName);//читаю из файла данных содержимое текущей строки и столбца BodyName Source[i][1]=oDmFile.GetNamedColumn(IndName);//читаю из файла данных содержимое текущей строки и столбца IndName Source[i][2]=oDmFile.GetNamedColumn("ABMSKO");//читаю из файла данных содержимое текущей строки и столбца ABMSKO if (i//передвигаюсь на следующую строку в файле > oDmFile.Close();//закрываю файл
проблема заключается в том, что при считывании второй записи и создании второго элемента массива первый элемент массива становится равным второму, при считывании третьей строки и создании третьего элемента массива первые два превращаются в третий и т.д. то есть, на выходе я имею массив идентичных элементов, равных последнему элементу массива. что я делаю не так?