1. Have a node.js development environment. If you need a guide to set this up, you should look at the node documentation as it gives an easy tutorial to do so.
2. A Text Editor
3. A CSV file to test
4. That's it
Installing the CSV Node module
After you've setup node.js open up a console and browse to where your project is installed.
Run the following command from the console:
npm install --save [email protected]
Using --save flag will install it to your local package.json if you don't yet have a package.json run npm init in your current working directory.
You must use version 0.3.7 for this sample code to work, as the package has since been updated and works quite a bit differently. 0.3.7 still works but may not work with the newest versions of node. I have tested this code using node 10.16.0
If you want to use the new version of the csv package I suggest referring to the documentation on the csv-parse package located at https://csv.js.org/parse/api/
Sample CSV file
You're going to need a CSV file to parse, so either you have one already, or you can copy the text below and paste it into a new file and call that file "mycsv.csv"
Sample Code Reading and Parsing the CSV file
Create a new file, and insert the following code into it. Make sure to read through what is going on behind the scenes.
Things to be aware of in your app.js code
In lines 7 through 11, we define the function called 'MyCSV' and the field names.
If your CSV file has multiple columns make sure you define this correctly to match your file.
On line 17 we define the location of the CSV file of which we are loading. Make sure you use the correct path here.
Start your App and Verify Functionality
Open a console and type the following Command:
You should see the following output in your console:
Now you should open a web-browser and navigate to your server. You should see it output the data in JSON format.
Using node.js and it's CSV module we can quickly and easily read and use data stored on the server and make it available to the client upon request. This is just one of many possible uses for it, but it is something that I'm asked about so often I figured many of you could find it useful. Enjoy!