Samuel
Samuel

Reputation: 2635

Update (write to) an object in a separate JS file using Node

I'm fairly new to Node, and am wracking my brains on how to achieve the following:

I have a config file that looks something like this:


// various es imports

export default {
  input: {
    index: 'src/index.ts',
    Button: 'src/Button/index.ts',
    Spinner: 'src/Spinner/index.ts',
    'icons/Notification': 'src/_shared/components/icons/Notification.tsx',
    'icons/Heart': 'src/_shared/components/icons/Heart.tsx',
  },
  //.. other properties
}

From my node script, i need to somehow read this file and do the following:

  1. Delete any entries in the input object that have a key starting with icons/
  2. Append new entries to the input object.
  3. Write these changes back to the original config file.

Is there a recommended way to do this in Node, i've been looking at a couple of libs, like replace-in-file but none seem to be suited to this particular case.

Upvotes: 2

Views: 2914

Answers (1)

Arthur Eudeline
Arthur Eudeline

Reputation: 655

Just faced the same concern, here is how I solved it :

1. Gets your file content

  • If it is not a .js file, then use fs.readFileSync (or fs.readFile) like so :
const fs = require('fs');
const path = require('path');
const myObjectAsString = fs.readFileSync( 
  path.join( process.cwd(), 'my-file.txt' ), // use path.join for cross-platform
  'utf-8' // Otherwise you'll get buffer instead of a plain string
);

// process myObjectAsString to get it as something you can manipulate

Here I am using process.cwd(), in case of a CLI app, it will gives you the current working directory path.

  • If it is a .js file (eg. a JavaScript config file like webpack.config.js for instance), then simply use require native function, as you would do with regular internal file or NPM module, and you will get all module.export content :
const path = require('path');
const myObject = require( path.join( process.cwd(), 'myFile.js') );

2. Modify your object as you want

// ...
myObject.options.foo = 'An awesome option value';

3. Then rewrite it back to the file

You can simply use fs.writeFileSync to achieve that :

// ...
fs.writeFileSync( path.join(process.cwd(), 'my-file.txt', myObject );

If you want to write a plain JavaScript Object, then you can use util.inspect() native method and you may also use fs.appendFileSync :

// ...

// If we wants to adds the 'module.exports = ' part before 
fs.writeFileSync( process.cwd() + '/file.js',  'module.exports = ');

// Writes the plain object to the file
fs.appendFileSync( process.cwd() + '/file.js',  util.inspect(options));

Upvotes: 2

Related Questions