user20862193
user20862193

Reputation:

How do I move al my code under one function in Javascript?

I have two scripts in JavaScript that allows my to write data to a text file. I want to move all of my code into one function called myFunction. I want to do this with just code and not copy and paste because I don’t have access to the source code.

My code for both programs are:

const fs = require('fs')          
// Data which will write in a file. 
let data = "Learning how to write in a file."           
// Write data in 'Output.txt' . 
fs.writeFile('Output.txt', data, (err) => {                  
  // In case of a error throw err.   
  if (err) throw err;

Can someone help me? I want to put this in a function by code and not copy and paste or manually doing it.

Upvotes: 0

Views: 29

Answers (1)

Samuel
Samuel

Reputation: 160

i think this is what you are asking for

function myFunction(data, fileName) {

  fs.writeFile(fileName, data, (err) => {
   
    if (err) throw err;
  });
}

// Call the function with different data and file names.
myFunction("Learning how to write in a file.", "testFileOut.txt");
myFunction("Writing to a different file.", "TestFileOther.txt");

Upvotes: 1

Related Questions