I'm working on a home-automation project (IoT) where my websocket server is a subscriber to a MQTT broker. It gets temperature and light intensity data from microcontroller. In a nutshell, the data are saved as JSON data, then I'll have to save the log of all the received data in a file. I used .writeFileSync() but it only resulted in [object Object] and I have to edit the data.JSON manually before I can run my program because it'll give an error if I don't.
This is the script:
var config = require('./data.json');
function writeData() {
fs.writeFileSync('data.json', config);
}
Then I tried changing it into
var config = require('./data.json');
let data2 = JSON.stringify(config);
function writeData() {
fs.writeFileSync('data-2.json', data2);
}
but I can't find the file named data-2.json.
Please help.
EDIT
I've called the writeData() function on this part:
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);
});
And the rest of the codes which follow are similar to this.
This should work:
const fs = require('fs');
let config = require('./data.json');
function writeData() {
fs.writeFileSync('data-2.json', JSON.stringify(config));
}
writeData();
Related
I'm trying to read data files from a directory called 'myfiles' using a script 'app.js'.
The file to be read depends on the configurations passed to 'app.js' by another process which generates the files 'log.txt' and 'config.json'.
'app.js' then reads the files 'log.txt' and 'config.json' and fetches a data file from 'myfiles' based on the file name received.
The files in 'myfiles' are labeled my-files1.txt, my-files2.txt, my-files3.txt, ... etc.
The problem is, I keep fetching the same file 'my-files1.txt', even though 'log.txt' and 'config.json' provide new names for files to fetch.
Could you please help me spot where the problem is?
Thanks for your help!
app.js:
const fs = require('fs');
const { resolve } = require('path');
function readLog() {
try {
return fs.readFileSync(__dirname + '/' + 'log.txt', 'utf8');
}
catch (err) {
return '';
}
}
function readConfig() {
try {
return fs.readFileSync(__dirname + '/' + 'config.json', 'utf8');
}
catch (err) {
return '';
}
}
let config = readConfig();
let log = readLog();
let cfg = JSON.parse(config);
let lcg = JSON.parse(log);
var currentPage = lcg.tPartition; // Current page to fetch
const numberOfPages = 10;
if((cfg.running!=true) && (Number(currentPage)>Number(numberOfPages))){
currentPage = 1;
}
function readDataset() {
try {
return fs.readFileSync(resolve(`./app/assets/myfiles/my-files${currentPage}.txt`), 'utf8');
}
catch (err) {
return err;
}
}
let dataset = readDataset();
const data = {
data1: dataset // set dataset as value of data1
}
module.exports={data};
you have written
let lcg = JSON.parse(log);
but your log is a txt file how can you parse it, is this the problem let me know if this worked by any chance;
I use watson assistant v1
My problem is that every time I make a call to the code in Nodejs, where I return the context, to have a coordinated conversation, the context is only updated once and I get stuck in a node of the conversation
this is my code
client.on('message', message => {
//general variables
var carpetaIndividual = <../../../>
var cuerpoMensaje = <....>
var emisorMensaje = <....>
//detect if context exists
if(fs.existsSync(carpetaIndividual+'/contexto.json')) {
var watsonContexto = require(carpetaIndividual+'/contexto.json');
var variableContexto = watsonContexto;
} else {
var variableContexto = {}
}
//conection with Watson Assistant
assistant.message(
{
input: { text: cuerpoMensaje },
workspaceId: '<>',
context: variableContexto,
})
.then(response => {
let messageWatson = response.result.output.text[0];
let contextoWatson = response.result.context;
console.log('Chatbot: ' + messageWatson);
//Save and create JSON file for context
fs.writeFile(carpetaIndividual+'/contexto.json', JSON.stringify(contextoWatson), 'utf8', function (err) {
if (err) {
console.error(err);
}
});
//Send messages to my application
client.sendMessage(emisorMensaje, messageWatson)
})
.catch(err => {
console.log(err);
});
}
client.initialize();
the context.json file is updated, but when it is read the code only reads the first update of the context.json file and not the other updates
This will be because you are using require to read the .json file. For all subsequent requires of an already-required file, the data is cached and reused.
You will need to use fs.readfile and JSON.parse
// detect if context exists
if (fs.existsSync(carpetaIndividual+'/contexto.json')) {
var watsonContexto = fs.readFileSync(carpetaIndividual+'/contexto.json');
// Converting to JSON
var variableContexto = JSON.parse(watsonContexto);
} else {
var variableContexto = {}
}
There is another subtle problem with your code, in that you are relying on
your async call to fs.writeFile completing before you read the file. This will be the case most of the time, but as you don't wait for the fs.writeFile to complete there is the chance that you may try to read the file, before it is written.
I need download and save file only with 'okhttp' library in 'node js' and not in java. but I don't know way to save my file on my computer. I need to use only okhttp library. please help me.
okhttp: https://www.npmjs.com/package/okhttp
const okhttp = require('okhttp');
var MimeBuilder = okhttp.MimeBuilder;
var Request = okhttp.Request;
var RequestBody = okhttp.RequestBody;
var RequestBuilder = okhttp.RequestBuilder;
var FormEncodingBuilder = okhttp.FormEncodingBuilder;
var MultiPartBuilder = okhttp.MultiPartBuilder;
new RequestBuilder().GET('http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png').bufferResponse().buildAndExecute().then(onComplete).catch(onError);
function onComplete(msg) {
console.log('success');
// !!!!!!!
// !!!!!!!
// now I need save blue-pushpin.png in my computer !
// !!!!!!!
// !!!!!!!
}
function onError(err) {
console.log('error');
}
First require fs (filesystem). The response data is available at msg.data; pass that to fs.writeFileSync along with the filename.
const fs = require('fs');
// ...
function onComplete(msg) {
console.log('success');
fs.writeFileSync('blue-pushpin.png', msg.data);
}
Im trying to send an answer to my websocket-server from a component which does not contain the websocket. My Websocket server looks like this:
componentDidMount() {
var ws = new WebSocket('ws:// URL');
ws.onmessage = this.handleMessage.bind(this);
...
}
How can I pass the "var ws" to another class or component. Or is it possible to make the websocket globally accessable?
Thank you very much for any help!
I found a solution with help from this question in stackoverflow:
visit:
React native: Always running component
I created a new class WebsocketController like this:
let instance = null;
class WebsocketController{
constructor() {
if(!instance){
instance = this;
}
this.ws = new WebSocket('ws://URL');
return instance;
}
}
export default WebsocketController
And then in my other class where I need my websocket I just called it like this:
let controller = new WebsocketController();
var ws = controller.ws;
websocket connection
keep this code in some file, name it with .js extenstion. ex: websocket.js
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
wss.on('connection', function connection(ws) {
// Store the remote systems IP address as "remoteIp".
var remoteIp = ws.upgradeReq.connection.remoteAddress;
// Print a log with the IP of the client that connected.
console.log('Connection received: ', remoteIp);
ws.send('You successfully connected to the websocket.');
ws.on('message',wss.broadcast);
});
In your app/website side. create .js file. Ex: client.js
var SERVER_URL = 'ws://127.0.0.1:8100';
var ws;
function connect() {
//alert('connect');
ws = new WebSocket(SERVER_URL, []);
// Set the function to be called when a message is received.
ws.onmessage = handleMessageReceived;
// Set the function to be called when we have connected to the server.
ws.onopen = handleConnected;
// Set the function to be called when an error occurs.
ws.onerror = handleError;
}
function handleMessageReceived(data) {
// Simply call logMessage(), passing the received data.
logMessage(data.data);
}
function handleConnected(data) {
// Create a log message which explains what has happened and includes
// the url we have connected too.
var logMsg = 'Connected to server: ' + data.target.url;
// Add the message to the log.
logMessage(logMsg)
ws.send("hi am raj");
}
function handleError(err) {
// Print the error to the console so we can debug it.
console.log("Error: ", err);
}
function logMessage(msg) {
// $apply() ensures that the elements on the page are updated
// with the new message.
$scope.$apply(function() {
//Append out new message to our message log. The \n means new line.
$scope.messageLog = $scope.messageLog + msg + "\n";
});
}
Please let me know if you face any issue with this code
I have the following code in index.js
var settingsFile = "config.json";
var settings = JSON.parse(require("fs").readFileSync(settingsFile));
const net = require('net');
const robot = require("robotjs");
const fs = require("fs");
var client;
var customKeys = {
"scroll_up":'robot.scrollMouse(50, "up");',
"scroll_down":"robot.scrollMouse(50,'down');"
}
function startCommunication(address,port) {
client = net.connect({port: port,host:address}, () => {
// 'connect' listener
console.log('connected to server!');
//client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
var string = data.toString();
console.log(settings.keys[string.substr(1)]);
if(string.substr(0,1) == "d") {
robot.keyToggle(settings.keys[string.substr(1)],"down");
} else {
robot.keyToggle(settings.keys[string.substr(1)],"up");
}
//client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
}
startCommunication(settings.address,settings.port);
i also have this code in config.json, aka what is parsed into the settings variable.
{
"port":5555,
"address":"192.168.1.118",
"keys":{
"KEY_A":"a",
"KEY_B":"b",
"KEY_X":"x",
"KEY_Y":"y",
"KEY_L":"y",
"KEY_R":"t",
"KEY_DUP":"up",
"KEY_DDOWN":"down",
"KEY_DLEFT":"left",
"KEY_DRIGHT":"right",
"KEY_START":"z",
"KEY_SELECT":"q"
}
}
What The Problem is is that when i get down to either robotjs.togglekeys statement i get the error
Error: Invalid key code specified.
This means that, as there error clearly states, it is getting an invalid keycode. I am guessing that is is some stupid mistake that I made. data in my testing is equal to "dKEY_DRIGHT". the variable string is equal to that but i need to get rid of the d in order for it to work. when i do the live console i am able to get the data that I need by using the same code but somethig goes wrong when it is being ran in the file. anything helps :)
you may try using node-key-sender to send keys presses to your operational system.
Install it with npm install --save-dev node-key-sender.
And send a key to the keyboard using:
var ks = require('node-key-sender');
ks.sendKey('up');
All the values of you config ('a', 'b', ...) are accepted by the lib. You can send them directly.
Check the documentation page for more information: https://www.npmjs.com/package/node-key-sender.