Home > Back-end >  Dynamic Input to a .txt file with Node.js fs
Dynamic Input to a .txt file with Node.js fs

Time:01-24

I have this code, and I am trying to get the data from the function addrBlk to display in console through fs.writeFile. I have tried with this code with these params and this function to display

```let addrBlk = (name, address1, address2, city, state, zip) => {
return name   "<br>"   address1   "<br>"   address2   
"<br>"   city   ", "   state   "  "   zip;
}```


```fs.writeFile("address.txt", addrBlk, (err) => {
if(err) {
    console.log(err);
}
else {
    console.log("Address written successfully, address is: ");
    console.log(fs.readFileSync("address.txt", "utf8"));
}
});```

and it returns exactly what the return says, I have also tried

```fs.writeFile("address.txt", `${name}`, (err) => {
if(err) {
    console.log(err);
}
else {
    console.log("Address written successfully, address is: ");
    console.log(fs.readFileSync("address.txt", "utf8"));
}
});```

and It returns an error saying name not defined. How can I return this data to a txt file with these params and return message??

CodePudding user response:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});


const fileName = 'address.txt'

const formatInput = (name, address1, address2, city, state, zip) => `${name}\n${address1}\n${address2}\n${city}, ${state} ${zip}`;

rl.question('Name: ', (name) => {
  rl.question('Address 1: ', (address1) => {
    rl.question('Address 2: ', (address2) => {
      rl.question('City: ', (city) => {
        rl.question('State: ', (state) => {
          rl.question('Zip: ', (zip) => {
            const data = formatInput(name, address1, address2, city, state, zip)

            fs.writeFile(fileName, data, (err) => {
              if (err) {
                console.log(err);
              } else {
                console.log("Address written successfully, address is: ");
                console.log(fs.readFileSync(fileName, "utf8"));
              }
            })
            rl.close();
          });
        });
      });
    });
  });
});
  • Related