Code Generation using CSV Files

Updated: 03 September 2023

Generating code from a CSV file

At times it may be necessary to generate a script or some code from a CSV File, this can be done using Node.js with a structure as follows:

1
const buildCode = ({param1. param2, param3}) => `
2
console.log(${param1}, ${param2 + param3})
3
`
4
5
const extractData = (line) => {
6
const items = line.split(',')
7
return {
8
param1: items[0],
9
param2: items[1],
10
param3: items[2]
11
}
12
}
13
14
const fs = require('fs')
15
16
const code = fs
17
.readFileSync('file.csv', 'utf8')
18
.split('\n')
19
.map(extractData)
20
.map(buildCode)
21
.join('')
22
23
fs.writeFileSync('newFile.js', code)
24
25
console.log('done')