5

I have this problem, i want to change a object value with a npm command (im using react) i put the example here:

const GLOBAL_CONSTANTS = {
  mobileIdNumber: '0',
  FOOTER_TEXT_LOGIN: 'v.3.8.215',
  DEFAULT_OFFSET: '-05:00',
  MENU: {
    ID_MODULE: 1,
  },
};
export default GLOBAL_CONSTANTS;

And i want that FOOTER_TEXT_LOGIN value change to v.3.8.216 or make a +1, when i execute npm run changeVersion, i already tried with sh but i dont knor very well how to use it.

1 Answer 1

4

This sort of thing can work.

const fs = require("fs");

// Pull the data from the file.
fs.readFile("./thing.json", 'utf-8', function (err, data) {
  // Error handling (this isn't the only place in the code where errors
  // can crop up, it's just the only place where I'm doing anything with
  // them :P
  if (err) {
    return console.log(err);
  }

  // Since I decided to make the configuration file into json, I can
  // read it with JSON.parse.
  const parsed = JSON.parse(data);

  // Split the version number from "0.1" to [0, 1].
  const value = parsed.value.split('.');

  // Coerce the second part of the value to a number and increment it.
  // Typically you'd want to make sure that if the value could not be
  // coerced, the process stops. I'll leave it up to you to implement
  // that though. 
  value[1] = +value[1] + 1;

  // Put the version number back together.
  parsed.value = value.join('.');

  // Replace the data in the file.
  fs.writeFile("./thing.json", JSON.stringify(parsed), () => {});
});

It's easier if your configuration is in json format. Otherwise you have to string parse javascript code, but the same basic concept works. Take the data apart, find the value you want to change, change it, then put the data back together.

Here's the json file (saved as thing.json) that my code updates.

{"value":"0.3"}

Once you have your script you can run it with node myscript.js or include it in one of your package.json scripts by prefixing an existing command with node myscript.js && or create a new command.

Sign up to request clarification or add additional context in comments.

1 Comment

ooo thanks i will check it and tell you how it works, thank you :3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.