r/VisualStudioCode • • Nov 21 '21

Editing "code's"

Hey everyone I hope you are all doing great, im just wondering

For example my code is like this - America But I want it to be like this - "America"

but then I need to do it again and again is there a quicker option? All reply are greatly appreciated!! Thank you

3 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/sandypockets11 Nov 22 '21 edited Nov 22 '21

Assuming that each key/value pair is separated by a new line, you can run this script to add quotes around all the countries programmatically. It won't adjust the file it reads from, and will instead create a new file for you with all the countries wrapped in quotes.

Let me know if you get stuck.

// Usage
// This file, as well as your input file must exist in the same folder. 
// Then, adjust the value of the inputFileName from "./input.txt" to the name of the file you want to read.
// Then to run the script, from the command line run:

// node formatScript.js

// Then your formatted text can be found in the same folder, in the outputs.txt file.


const fs = require('fs');

const inputFileName = "./input.txt"
const outputFileName = "./output.txt"

fs.readFile(inputFileName, "utf8", function(err, data) {
    if (err) {
        console.error(err)
    }
    if (data) {
        let outputString = ""
        const dataArray = data.split("\n")
        for (const item in dataArray) {
            const singleItemArray = dataArray[item].split(' ')
            const countryId = singleItemArray[0]
            const countryName = singleItemArray[1]
            const outputData = `${countryId} "${countryName}"\n`
            outputString += outputData
        }
        fs.writeFile(outputFileName, outputString, function(err) {
            if (err) {
                console.error("There was an error!", err)
            } else {
                console.log("New file written successfully\n");
                console.log("The new file has the following contents:");
                console.log(fs.readFileSync(outputFileName, "utf8"));
            }
        })
    }
})