I have this code, and I am trying to get the data from the function addrBlk to display in console through fs.writeFile. I have tried with this code with these params and this function to display
```let addrBlk = (name, address1, address2, city, state, zip) => {
return name + "<br>" + address1 + "<br>" + address2 +
"<br>" + city + ", " + state + " " + zip;
}```
```fs.writeFile("address.txt", addrBlk, (err) => {
if(err) {
console.log(err);
}
else {
console.log("Address written successfully, address is: ");
console.log(fs.readFileSync("address.txt", "utf8"));
}
});```
and it returns exactly what the return says, I have also tried
```fs.writeFile("address.txt", `${name}`, (err) => {
if(err) {
console.log(err);
}
else {
console.log("Address written successfully, address is: ");
console.log(fs.readFileSync("address.txt", "utf8"));
}
});```
and It returns an error saying name not defined. How can I return this data to a txt file with these params and return message??
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const fileName = 'address.txt'
const formatInput = (name, address1, address2, city, state, zip) => `${name}\n${address1}\n${address2}\n${city}, ${state} ${zip}`;
rl.question('Name: ', (name) => {
rl.question('Address 1: ', (address1) => {
rl.question('Address 2: ', (address2) => {
rl.question('City: ', (city) => {
rl.question('State: ', (state) => {
rl.question('Zip: ', (zip) => {
const data = formatInput(name, address1, address2, city, state, zip)
fs.writeFile(fileName, data, (err) => {
if (err) {
console.log(err);
} else {
console.log("Address written successfully, address is: ");
console.log(fs.readFileSync(fileName, "utf8"));
}
})
rl.close();
});
});
});
});
});
});
Related
I am using react with firebase firestore to insert a complete collection with documents that does not already exist in firebase firestore .
With my code however no collection is inserted and I get no error as if nothing happened.
This is the code that returns my json
createJson.js
const jsonArray = [{name:"Bill" , age : "5"} ,{name:"Jom" , age : "3"} ]
return jsonArray;
insertJson.js
import 'firebase/firestore';
const db = firebase.firestore();
export const insertJson = (jsn)=>{
try{
jsn.forEach(itm=>{
let id = db.collection("doctors").doc().id;
db
.collection("doctors")
.doc(id)
.set(itm)
.then(doc=>{
console.log("Doc inserted with " +doc.id);
})
});
}catch(err){
console.log("Error : " +err);
}
}
App.js
useEffect(()=>{
const j = createJson();
insertJson(j);
},[])
So in other words no collection is created with my script with the docs inside .
I would appreciate your help .
You should use the Firestore add() method and Promise.all() as follows:
export const insertJson = (jsn) => {
try {
const promises = [];
jsn.forEach((itm) => {
promises.push(db.collection('doctors').add(itm));
});
Promise.all(promises).then((results) => {
console.log(results.length + ' doctors added');
});
} catch (err) {
console.log('Error : ' + err);
}
}
or, with map():
export const insertJson = (jsn) => {
try {
Promise.all(jsn.map((itm) => db.collection('doctors').add(itm))).then(
(results) => {
console.log(jsn.length + ' doctors added');
}
);
} catch (err) {
console.log('Error : ' + err);
}
}
If the number of doctors is less than 500 you could also use a batched write.
export const insertJson = (jsn) => {
try {
const batch = db.batch();
jsn.forEach((itm) => {
const docRef = db.collection('doctors').doc();
batch.set(docRef, itm);
});
batch.commit().then((results) => {
console.log('doctors added');
});
} catch (err) {
console.log('Error : ' + err);
}
}
I'm fetching data form a API and since I have to collect lots of data, I'm using the setTimeOut function to delay the requests by 3s each. But, when I try to run the code, the for loop only run once and finishes the program.
const fs = require('fs')
const { JSDOM } = require("jsdom")
const { window } = new JSDOM("")
const $ = require("jquery")(window)
const path = require('path')
const fetchArt = require('./utils/fetchArt.js')
const { data } = require('jquery')
const { resolve } = require('path')
let replacer = RegExp(' ', 'g')
let slash = RegExp('/', 'g')
const requestArtSongs = (artist) => {
return $.getJSON("https://www.vagalume.com.br/" + artist + "/index.js").then(
function (data) {
return data.artist.lyrics.item
}
)
}
const map = (lang) => {
switch (lang) {
case 1: return 'pt'
case 2: return 'en'
default: return lang
}
}
const requestMusic = (artist, song) => {
return $.getJSON(
"https://api.vagalume.com.br/search.php"
+ "?art=" + artist
+ "&mus=" + song
+ "&apikey={key}"
).then(function (data) {
return [data.mus[0].text, data.mus[0].lang]
})
}
const makeRequest = (art, songs) => {
songs.forEach((song, i) => {
delay(3000 * (i+1))
.then(() => makeSongRequest(art, song.desc))
})
}
const writeFile = (art, songName, mus) => {
gen = gens[0]
let music = {
artist: art,
song: {
name: songName,
text: mus[0],
lang: map(mus[1])
}
}
if (fs.existsSync(path.join(__dirname, 'Genders', gen, art))) {
fs.writeFile(path.join(__dirname, 'Genders', gen, art, `${songName.replace(slash, '')}.json`),
JSON.stringify(music, null, 4),
(err) => {
if (err) throw err
console.log('Song ' + songName + ' written!')
})
} else {
fs.mkdir(path.join(__dirname, 'Genders', gen, art), { recursive: true }, err => {
if (err) throw err
fs.writeFile(path.join(__dirname, 'Genders', gen, art, `${songName.replace(slash, '')}.json`),
JSON.stringify(music, null, 4),
(err) => {
if (err) throw err
console.log('Song ' + songName + ' written!')
})
})
}
}
const makeSongRequest = (art, songName) => {
requestMusic(art, songName)
.then(mus => {
writeFile(art, songName, mus)
})
}
const delay = t => new Promise (resolve => setTimeout(resolve, t))
const writeSongs = (artist) => {
art = artist.replace(replacer, '-').toLowerCase()
return new Promise(() => {
requestArtSongs(art)
.then((songs) => {
makeRequest(artist, songs)
})
})
}
const main = async () => {
let gens = ['Funk']
for (let gen of gens){
let arts = await fetchArt(gen)
for (let art of arts) {
await writeSongs(art)
}
}
}
main()
On my main function, I'm trying to fetch lyrics from the API. For each gender (in this case, only 'Funk') I get the artists that sing that gender. Then, for each artist I run the writeSongs function that does lots of stuff.
I'm using Node JS to do all the work.
I have this index.html file that talks to Raspberry pi 3 running a bleno app over BLE.
<!-- <!DOCTYPE html> -->
<html>
<head>
<meta charset="utf-8">
<title>bluetooth</title>
<script type="text/javascript">
var serv;
var readVal="";
function onButtonClick() {
console.log('clciked');
let filters = [];
var options1 = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
let options = {};
var tem = '00010000-89BD-43C8-9231-40F6E305F96D'.toLowerCase();
filters.push({services: [tem]});
options.acceptAllDevices = false;
options.filters = filters;
console.log('Requesting Bluetooth Device...');
console.log('with ' + JSON.stringify(options));
var listn;
if(navigator.bluetooth){
document.getElementById('result').innerHTML = "Bluetooth Supported";
}
else{
document.getElementById('result').innerHTML = "Bluetooth not Supported";
}
function success(pos) {
var crd = pos.coords;
console.log(crd);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
console.log(navigator);
navigator.geolocation.getCurrentPosition(success, error, options1);
// navigator.
let decoder = new TextDecoder('utf-8');
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('> Name: ' + device.name);
console.log('> Id: ' + device.id);
console.log('> Connected: ' + device.gatt.connected);
return device.gatt.connect();
})
.then(server => {
return server.getPrimaryService(tem);
})
.then(service => {
serv = service;
console.log(service);
return service.getCharacteristic('00010010-89bd-43c8-9231-40f6e305f96d');
})
.then(characteristic => {
// console.log(characteristic);
return characteristic.readValue();
})
.then(value => {
let decoder = new TextDecoder('utf-8');
var str = decoder.decode(value);
readVal = str;
console.log(value);
console.log(value.toString());
console.log(str);
})
.catch(error => {
console.log('Argh! ' + error);
});
}
function onSend() {
serv.getCharacteristics().then(characteristics =>{
// console.log(characteristics);
var charact;
for(var i = 0; i < characteristics.length; i++){
var ob = characteristics[i];
if(ob['properties']['write'] === true){
charact = ob;
}
}
console.log(charact);
var Encoder = new TextEncoder("utf-8");
console.log(readVal);
var b = Encoder.encode(readVal);
console.log(b);
charact.writeValue(b);
})
.then(_ => {
console.log('wrote data');
})
.catch(err => {
console.log(err);
});
}
</script>
</head>
<body>
<button id = "b1" onclick="onButtonClick();">Click</button>
<h1 id = 'result'></h1>
<div id = 'networks'></div>
<button id="send" onclick="onSend();">Send Back</button>
</body>
</html>
I can read the characteristics from the ble peripheral, but I get a DOMException GATToperation failed due to reasons unknown at index.html line 0.
My bleno app on the Pi, app.js
var bleno = require('bleno');
var fs = require('fs');
var scannedNetworks = [];
const WIFI_SERVICE_UUID = "00010000-89BD-43C8-9231-40F6E305F96D";
const ARGUMENT_1_UUID = "00010001-89BD-43C8-9231-40F6E305F96D";
const RESULT_UUID = "00010010-89BD-43C8-9231-40F6E305F96D";
class ArgumentCharacteristic extends bleno.Characteristic {
constructor(uuid, name) {
super({
uuid: uuid,
properties: ["write"],
value: null,
descriptors: [
new bleno.Descriptor({
uuid: "2901",
value: name
})
]
});
this.argument = 0;
this.name = name;
}
onWriteRequest(data, offset, withoutResponse, callback) {
try {
if(data.length != 1) {
callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
return;
}
this.argument = data.readUInt8();
let decoder = new TextDecoder('utf-8');
var str = decoder.decode(value);
console.log(`Argument ${this.name} is now ${this.argument}`);
console.log(str);
callback(this.RESULT_SUCCESS);
} catch (err) {
console.error(err);
callback(this.RESULT_UNLIKELY_ERROR);
}
}
}
class ResultCharacteristic extends bleno.Characteristic {
constructor() {
super({
uuid: RESULT_UUID,
properties: ["read"],
value: null,
descriptors: [
new bleno.Descriptor({
uuid: "2901",
value: "Calculation result"
})
]
});
//this.calcResultFunc = calcResultFunc;
}
onReadRequest(offset, callback) {
try {
fs.readFile('./weights.txt', (err,dat)=>{
if(!err){
var result = dat.toString();
console.log(`Returning result: ${result}`);
let data = new Buffer(result);
//data.writeUInt8(result, 0);
console.log(data);
callback(this.RESULT_SUCCESS, data);
}
});
} catch (err) {
console.error(err);
callback(this.RESULT_UNLIKELY_ERROR);
}
}
}
console.log("Starting bleno...");
bleno.on("stateChange", state => {
if (state === "poweredOn") {
bleno.startAdvertising("Visualizer thresholds", [WIFI_SERVICE_UUID], err => {
if (err) console.log(err);
});
} else {
console.log("Stopping...");
bleno.stopAdvertising();
}
});
bleno.on("advertisingStart", err => {
console.log("Configuring services...");
if(err) {
console.error(err);
return;
}
let argument1 = new ArgumentCharacteristic(ARGUMENT_1_UUID, "Argument 1");
let result = new ResultCharacteristic();
let calculator = new bleno.PrimaryService({
uuid: WIFI_SERVICE_UUID,
characteristics: [
result,
argument1
]
});
bleno.setServices([calculator], err => {
if(err)
console.log(err);
else
console.log("Services configured");
});
});
// some diagnostics
bleno.on("stateChange", state => console.log(`Bleno: Adapter changed state to ${state}`));
bleno.on("advertisingStart", err => console.log("Bleno: advertisingStart"));
bleno.on("advertisingStartError", err => console.log("Bleno: advertisingStartError"));
bleno.on("advertisingStop", err => console.log("Bleno: advertisingStop"));
bleno.on("servicesSet", err => console.log("Bleno: servicesSet"));
bleno.on("servicesSetError", err => console.log("Bleno: servicesSetError"));
bleno.on("accept", clientAddress => console.log(`Bleno: accept ${clientAddress}`));
bleno.on("disconnect", clientAddress => console.log(`Bleno: disconnect ${clientAddress}`));
Can you guys help me where I am going wrong?
Thanks
I'm making an iOS app and I have this problem now.
I'd like to count the number of unread messages in database and assign it in a database different closure. Like below.
exports.arrivalNotifications = functions.database.ref('/trips/{tripId}')
.onCreate((snap, context) => {
const data = snap.val();
const uid = data.uid;
var counter = 0
admin.database().ref('/messages/').on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
if (childData.read === false) {
counter += 1
}
});
})
return admin.database().ref('/users/' + uid).once('value', snapshot => {
const data = snapshot.val();
const username = data.username
var payload = {
notification: {
title: username ' has ' + counter + " unread message.",
body: 'Press for more'
}
}
admin.messaging().sendToDevice(toUser.fcmToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
return null;
})
.catch(function(error) {
console.log("Error sending message:", error);
});
})
})
So I want to use the counter in the payload but I can't find the way to do it. I'm not familiar with JavaScript so if someone can help me I'd appreciate.
I would write your Cloud Function as follow. Please note that I could not test it and it may need some fine-tuning/debugging... especially since it implies chaining several promises.
exports.arrivalNotifications = functions.database.ref('/trips/{tripId}').onCreate((snap, context) => {
const data = snap.val();
const uid = data.uid;
let counter = 0;
return admin.database().ref('/messages/').once('value')
.then(snapshot => {
snapshot.forEach(function (childSnapshot) {
const childData = childSnapshot.val();
if (childData.read === false) {
counter += 1;
}
});
return admin.database().ref('/users/' + uid).once('value');
})
.then(snapshot => {
const data = snapshot.val();
const username = data.username;
const payload = {
notification: {
title: username + ' has ' + counter + ' unread message.',
body: 'Press for more'
}
};
return admin.messaging().sendToDevice(toUser.fcmToken, payload);
})
.then(response => {
console.log("Successfully sent message:", response);
return null;
})
.catch(error => {
console.log("Error sending message:", error);
});
});
I am trying to search my local db for a user by email, but when I try to reference a function that does that from a different js file, via an import, I get undefined results. I have searched a bit on Stack about this issue I am having, and heard of something referred to as a callback, is this something that I would need to implement? If so could you point me to an example ?
Thanks in advance!
Here is my code that is exported (db.js file) :
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
exports.findEmail = (email) => {
// console.log('hi');
session
.run("MATCH (a:Person) WHERE a.email = {email} RETURN a.name AS name, a.email AS email, a.location AS location", {
email: email
})
.then((result) => {
let result_string = '';
result.records.forEach((record) => {
console.log(record._fields);
result_string += record._fields + ' ';
});
return result_string;
})
.catch((e) => {
return ('error : ' + JSON.stringify(e));
})
}
Here is my code calling the export : (test.js)
var tester = require('./db.js');
let temp = tester.findEmail("testemail#yahoo.com");
console.log(temp);
The thing is that JS is asynchronous, and you using it as it is synchronous code.
Can you try this one, should work:
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
const findEmail = (email, callback) => {
console.log('hi :', email);
session
.run("MATCH (a:Person) WHERE a.email = {email} RETURN a.name AS name, a.email AS email, a.location AS location", {
email: email
})
.then((result) => {
let result_string = '';
result.records.forEach((record) => {
console.log(record._fields);
result_string += record._fields + ' ';
});
return callback(null, result_string);
})
.catch((e) => {
return callback('error : ' + JSON.stringify(e)));
})
}
module.exports = {
findEmail
};
Then in test.js:
var tester = require('./db');
tester.findEmail("testemail#yahoo.com", (err, temp) => {
if (err) return console.error(err);
console.log(temp);
} );
The idea behind this is that all the flow in db file is asynchronous.
So in order to catch result you need to pass the function, callback, which will be triggered when the ansynchronous flow is done.