copy a json file in javascript

To copy a JSON file in JavaScript, assuming you are working on the server-side with Node.js, you can use the built-in fs module. Here is an example code snippet to copy a JSON file:

index.tsx
const fs = require('fs');

// Path to the source file
const sourcePath = './data/source.json';

// Path to the destination file
const destPath = './data/destination.json';

// Read the content of the source file
const sourceData = fs.readFileSync(sourcePath, 'utf-8');

// Write the content to the destination file
fs.writeFileSync(destPath, sourceData);

console.log('JSON file copied successfully!');
403 chars
16 lines

In this code, we first require the fs module to have access to its methods. Then, we define the paths to the source and destination JSON files.

We use readFileSync to read the content of the source file and store it in a variable as a string. Note that we specify the encoding to be 'utf-8' since we are dealing with a JSON file.

Finally, we use writeFileSync to write the content of the source file to the destination file. Again, we use 'utf-8' encoding to ensure that the file is written as a JSON string, rather than a buffer or binary data.

If all goes well, the console will log the success message, indicating that the JSON file has been copied.

gistlibby LogSnag