Home > front end >  how to update name with variable in nodejs?
how to update name with variable in nodejs?

Time:11-20

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

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 ?

CodePudding user response:

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:

  • Related