Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to update name with variable in nodejs?

I have dummy template of package.json . I want to copy dummy package.json inside some folder (Application name folder) and update the name from from package.json . can we do this in node js.

here is my source package.json file

{
  "name":"$name"
}

I tried like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const fs = require('fs');
const prompt = require('prompt-sync')();

let appName = prompt('what is application name..?');
if(!appName){
    appName='temp'
}

console.log(`Application name is ${appName}`);

if (!fs.existsSync(`${appName}`)){
    fs.mkdirSync(`${appName}`);
}

fs.copyFile('./source/package.json', `${appName}/package.json`, (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});

when I run node index.js . it ask "application name" user enter application name let say example (abc). It create a folder abc and put package.json file which is working fine.

Now issue is I want the content of package.json is

{
  "name":"abc"
}

can we replace the name variable ?

>Solution :

Let’s say you have ./abc/package.json and its contents look like this:

{
  "name": "$name",
  "version": "0.1.0"
}

If you want to modify just the name field, you’ll have to:

  1. read the package data as JSON text
  2. parse it as an object
  3. modify the name property to your desired value
  4. write it back to the file

A minimal example of doing that in a script might look like this:

./rename.mjs:

import {readFile, writeFile} from 'node:fs/promises';

const pkgPath = './abc/package.json';
const textEncoding = {encoding: 'utf-8'};

const json = await readFile(pkgPath, textEncoding);

const pkgData = JSON.parse(json);

pkgData.name = 'abc';

const prettyJson = JSON.stringify(pkgData, null, 2);

await writeFile(pkgPath, prettyJson, textEncoding);

After you run it:

node rename.mjs

The package contents will be updated:

{
  "name": "abc",
  "version": "0.1.0"
}

Ref:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading