Michael Joseph Aubry Michael Joseph Aubry - 4 months ago 17
Javascript Question

ES6 Node.js import then rewrite the file?

Is it a possible to import a JSON file in node.js update some properties in the JSON then write the new data back into place?

Would it be better to use

fs
to read the file then write the file again?

I am trying to whip up a stupid simple prototype DB using JSON.

export const Users = [
{
username: 'Mike'
}
]

export const Websites = [
{
owner: 'Mike',
website: 'michael-aubry',
build: {
header: {
component: 'header',
navigation: 'standard'
},
main: {
works: true,
card: 1
}
}
}
]

export const Works = [
{
owner: 'Mike',
items: [
{title: 'Dribbble Thanks', image_src: './dribbble_thanks.png'},
{title: 'My WIP', image_src: 'bloomthat.png'},
{title: 'Michael Angelo', image_src: 'https://d13yacurqjgara.cloudfront.net/users/371472/screenshots/2847709/studio-minted-case-studies-promo.jpg'},
{title: 'Beautiful Art', image_src: 'https://d13yacurqjgara.cloudfront.net/users/4094/screenshots/2846992/drib106.jpg'}
]
}
]

Answer

Let's think about this in a slightly different way.

We can't use import to write back to a JSON file, and if the JSON file shouldn't permanently change, we don't necessarily want to write back to it.

What if you had a module that read the JSON file, and then other files would import this module to use and manipulate that data?

// data.json
{
  "users": ...,
  "websites": ...,
  "works": ...
}

// data.js
import data from './data.json'
export default data

And now you can import from data.js and modify those values.

Comments