Skip to content Skip to sidebar Skip to footer

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 { i

Solution 1:

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));

Post a Comment for "Update (write To) An Object In A Separate Js File Using Node"