Tips for saving JSON data in a file with writeFileSync

I'm currently working on a project related to home automation using IoT technology. In this project, my websocket server acts as a subscriber to a MQTT broker, receiving temperature and light intensity data from a microcontroller in the form of JSON data. My goal is to save all received data logs into a file; however, when I attempted to do so using .writeFileSync(), it only displayed [object Object]. To remedy this, I had to manually edit the data.JSON file before running my program to avoid encountering errors.

Below is the script structure:

var config = require('./data.json');

function writeData() {
    fs.writeFileSync('data.json', config);
}

The next approach I tried was:

var config = require('./data.json');
let data2 = JSON.stringify(config);

function writeData() {
   fs.writeFileSync('data-2.json', data2);
}

However, I encountered difficulties in locating the file named data-2.json.

Any assistance with this issue would be greatly appreciated.

EDIT

I have invoked the writeData() function within this section of the code:

    s.on('dev:on', function (id) {
    if (id == 'lamp1') {
        config.lamp1 = true;
    } else if (id == 'fan1") {
        config.fan1 = true;
    }
    client.publish(id, "true");
    writeData();
    console.log('Device ON RECEIVED for ' + id);
});

The remaining sections of the code resemble this snippet.

Answer №1

Here's a solution that should function correctly:

const fs = require('fs');
let configuration = require('./data.json');

function saveData() {
    fs.writeFileSync('new-data.json', JSON.stringify(configuration));
}

saveData();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selecting input elements using jQuery with the li option

In my HTML, I have a list of input textboxes with the class "txtdate" and another list of input textboxes with the class "txthrs". Here is an example of how they are structured: <div id="dvlitr"> <li id="0"> <label class="txtdatewrapper"> ...

POST request in Ajax with NodeJs/MongoDB/Mongoose causing an Uncaught TypeError: Illegal invocation

Whenever I attempt to make a POST request using Ajax/Jquery, I keep encountering an error in the console. The specific errors are on lines 67 and 31 in the createTeam.js file: $.ajax({ //line 67 sendInvitation(teamID,_companyName,teamName) //lin ...

What's wrong with this old jQuery code?

After stumbling upon this page: Page I was thrilled to find exactly what I was looking for. However, after copying the code, it doesn't seem to work. $(function() { var scntDiv = $('#p_scents'); var i = $('#p_s ...

Is there a way to use Javascript to detect if the value of a control on an ASP.Net page has been modified?

Within my web page, I have integrated a FormView that transitions to Edit mode when the user clicks the edit button. To enhance user experience, I have implemented a JavaScript onbeforeunload function that triggers a confirmation dialog if the user tries t ...

Search for all fields using Mongoose with the $regex operator

Imagine having a model like this: var advertisement = mongoose.Schema({ username: String, text: String, locations: Array, days: Array, phone: Object, images: Array, age: Number, height: String, sex: String, cate ...

Transforming a callback function into a Promise: A step-by-step guide

I'm currently utilizing Bluebird promises and attempting to make the following function work with Promisify: var jwt = require('jsonwebtoken'); function _test_encode() { var cert = fs.readFileSync('public.pub'); return j ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

Iterating over an array within an if statement to validate if all elements meet the criteria

In my code, I have a variable named 'fieldCount' and it is currently set to 5 which represents the number of fields that I have. How can I refactor the following code without explicitly mentioning each index: if ( fields[0].checkValidity() &a ...

The CLI feature is not compatible with NextJS Drizzle-Kit

I'm currently utilizing the drizzle auth template and attempting to customize it for Role Based Authentication. I've made adjustments in the db.ts file to incorporate roles. import { drizzle } from 'drizzle-orm/postgres-js'; import { pg ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Firefox returns empty computed value in getComputedStyle function

When I use getComputedStyle on an element that has defined properties for left, right, and bottom, I noticed that Chrome returns 'auto' as the value for top, whereas Firefox returns the pixel value. However, interestingly, the top value does not ...

What are the methods for handling JSON type in a web server?

Hey there! I'm currently working on making an AJAX call from the browser to a web service. The data is being sent as JSON from the browser to the web service. I'm wondering if there is a different way to retrieve it as a string and then deseriali ...

Highcharts revolutionizing the way data is displayed with real-time data integration in 202

Struggling with an ajax request that should return a datetime array for use in highcharts. The data is coming back as a json array like this: [[1395489600000,29.010971409934],[1395493200000,29.234899961948],[1395496800000,29.712949994206],[1395500400000,2 ...

I am attempting to utilize the code below in Eclipse to extract a JSON Array using JsonPath, but I am encountering an error

\import Files.Payload; import io.restassured.path.json.JsonPath; public class complexJsonParse { public static void main(String[] args) { // TODO Auto-generated method stub JsonPath js=new JsonPath(Payload.CoursePrice()) ...

``node: encountered an issue when attempting to load shared libraries: libicui18n.so.62 could not be opened because the shared object file does not exist in the

After a recent update to my Ubuntu version, I started encountering an error message every time I try to run a node or npm command: node: error while loading shared libraries: libicui18n.so.62: cannot open shared object file: No such file or directory Can ...

Verify whether the input includes a specific value or a different one

Can someone help me with a simple task of checking if a textarea contains the value "12" OR "34"? I have tried the code below but it doesn't seem to work. Any suggestions? function check() { if (V1.value == ('12' || '34')) { ...

"Unlocking the potential of Framework7 + Vue to seamlessly integrate footers into panels

I am currently working on a website and looking to incorporate the Framework7 with Vue. The task at hand involves creating a side panel with a list inside it. One specific requirement is to add an exit icon at the end of this panel. Any assistance in ach ...

Steps to retrieve a base64 image using Cordova's FileTransfer feature

Recently, I encountered an issue with downloading base-64 images using the Cordova file transfer protocol. When I tried to provide a remote server path like "", the download worked perfectly. However, when I attempted to use a base-64 image path for the fi ...

Incorporate animated SVG directly into Vue templates without using any additional enclosures

I need to incorporate dynamic SVG code into my <template> without using v-html or any wrapper around it. The desired end result should look like the following, but template does not support v-html to achieve this. If there is a way to accomplish thi ...

What is the best approach to transpiling TypeScript aliased paths to JavaScript?

I am currently facing an issue with my TypeScript project where I need to transpile it into executable JavaScript while using path aliases for my NPM package development. One specific scenario involves importing a method from the lib directory without spe ...