Read file and write file JSON - node.js

In this, I am trying to make a hit counter where every time someone visits my site the variable will be read from the views.json file one is added to the number and then the .json will be updated with the new number. However when I tested it in a repl.it project I got an error saying
ReferenceError: writeFileSync is not defined
at /home/runner/hit-counter/index.js:6:1
at Script.runInContext (vm.js:133:20)
at Object.<anonymous> (/run_dir/interp.js:156:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
I don't know what this means if you know please tell me and how I may be able to fix it.
the reply project link:https://hit-counter.cohense.repl.run/
The JavaScript (ES6)
const fs = require('fs');
let views = fs.readFileSync('views.json');
views = JSON.parse(views);
views.total++;
let data = JSON.stringify(views, null, 2);
writeFileSync("views.json", data, finished);
function finished(err) {
if (views = JSON.parse(views)) {
console.log("Your view has been accounted for!")
} else {
console.error("Error occured please reload the page =(")
}
};
the JSON
{
"totalViews": 1
}

You can do like this, just fixed some errors.
Oh, you should use writeFileSync, to avoid that the file will not be edited at same time.
The question is, why don't you use a DB? It's a lot faster and fix concurrency writes.
var fs = require('fs')
var data = fs.readFileSync('views.json')
var views = JSON.parse(data);
console.log(views);
views.total = views.total + 1;
var data = JSON.stringify(views, null, 2)
writeFileSync("views.json", data, ()=>{
console.log("Your View Has Been Accounted For!")
})

I found out what I did wrong I didn't use fs.
writeFileSync("views.json", data, finished);
When I just needed to do
fs.writeFileSync("views.json", data[,finished]);

Related

Node.js - Function not working when exported

Good day everyone,
First off, thanks for always being such an amazing community. You all really are helping me a ton with learning and bettering my programming and development!
I have a small question related to the module.exports within Node.js. The function below runs with no issues when called on directly:
const fs = require('fs')
const {nanoid} = require('nanoid')
const createStormDB = () => {
return new Promise((resolve, reject) => {
try{
const id = nanoid(4)
const date = new Date() // Create date string for file naming
let dateString = `${date.toISOString().split('T')[0]}` // Create date string for file naming
let fileName = `${dateString}_deals_${id}.stormdb` // Create date string for file naming
fs.openSync(`../StormDB/${fileName}`, 'w')
resolve(fileName)
}catch(err){
reject(err)
}
})
}
module.exports = createStormDB
It creates a file with a specific name within in specific folder. But when I use module.exports = createStormDB I am greeted with the following error:
(node:12516) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '../StormDB/2021-07-19_deals_gYmJ.stormdb'
at Object.openSync (fs.js:476:3)
at C:\Node\Pipedrive-Connector\PipeDriveRequest\scripts\createStormDBFile.js:11:16
at new Promise (<anonymous>)
at createStormDB (C:\Node\Pipedrive-Connector\PipeDriveRequest\scripts\createStormDBFile.js:5:12)
at Object.<anonymous> (C:\Node\Pipedrive-Connector\PipeDriveRequest\play.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Is there something I am misunderstanding when it comes to exporting modules? I'm importing this module using the require option! Thanks so much for the help!
The .. relative path in the function is relative to the calling scripts current working directory, not the directory the file is in.
Assuming from your path setup and description the database is in: C:\Node\Pipedrive-Connector\PipeDriveRequest\StormDB
If you want the database path to remain relative to the javascript file containing the function, use __dirname
const path = require('path')
const db_path = path.join(__dirname, '..', 'StormDB', filename)
fs.openSync(db_path, 'w')

How to get browser Idle time in NodeJS script?

I'm planning to create simple users browser tracking system, where I want to track whether user is idle for certain time or not. I thought NodeJS would be the ideal choice.
Found certain NodeJS modules as well. But the problem is that all of them are using document. But in my case there is not document object is available, as I'm using pure NodeJS where there is no browser interaction is possible as I want to tack browser inactivity in background.
I tried below NPM Module.
https://www.npmjs.com/package/away
Which gives below error.
ReferenceError: document is not defined
at Object.<anonymous> (/media/d/Projects/PHPProjects/ets/node_modules/away/index.js:16:14)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/media/d/Projects/PHPProjects/ets/index.js:16:16)
at Module._compile (module.js:571:32)
Here is my implementation
// HTTP Module
var http = require('http');
// OS Utility Module
var os = require('os-utils');
// Native OS object
var osNative = require('os');
// MySQL Connection Setup
var mysql = require('mysql');
// Create server
var server = http.createServer(function() {});
var away = require('away');
// detect users who are idle for 10 seconds
var timer = away(5000);
timer.on('idle', function() {
console.log('user is idle');
});
timer.on('active', function() {
console.log('user is active');
});

Does Buffer have a compare method?

I am reading NodeJS tutorial and I have reached to this page.
There is an example code for the compare method of Buffer objects:
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 +" comes before " + buffer2);
}else if(result == 0){
console.log(buffer1 +" is same as " + buffer2);
}else {
console.log(buffer1 +" comes after " + buffer2);
}
which throws this:
Executing the program.... $node main.js
/web/com/1460883529_55644/main.js:3 var result =
buffer1.compare(buffer2);
^ TypeError: Object ABC has no method 'compare' at Object. (/web/com/1460883529_55644/main.js:3:22)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
It is strange that in the trace the object is called ABC and not buffer1 and that there is no compare method according to the trace. The example which tried to clarify the compare method confused me. Can someone explain what happened here?
That tutorial site uses Node v0.10 which is very old and does not even support the methods used in the tutorial itself!
The code works fine in the current release of Node, v4.4.3, as well as any other recent release. The relevant documentation for compare() is here: https://nodejs.org/api/buffer.html#buffer_buf_compare_otherbuffer
As an aside, you may want to stop using new Buffer() in favor of the more recent Buffer.from() API. This is said to improve code safety.

Can't update elements which are inside the array

Let's say I have this
userinfo={
userDetails:
{
username:"",
password:"",
cookie:"",
firstname:"",
lastname:"",
phonenumber:"",
postalcode:"",
country:""
},
applicationsInfo:[
{
application:"",
consumerKey:"",
accessToken:""
}
]
}
First I created user and latter I am to update applicationsInfo section when user creates an application. First I tried this way and It works
var consumerKey="asdyfsatfdtyafydsahyadsy";
var findCon={"userDetails.username":"someName"};
db.find(findCon,function(err,docs){
if(err){
console.log(err);
}else{
var updateCon={$set:{"applicationsInfo.0.consumerKey":consumerKey}};
db.update(findCon,updateCon,{},function(err,docs){
console.log(docs);
});
}
});
But actually what I want is update some selected one I tried that in this way.
........
var appNum=0;
var updateCon={$set:{"applicationsInfo."+appNum+".consumerKey":consumerKey}};
then I start my node server then I got error like this.
/home/jobs/nodeserver/routes/initusers.js:180
"applicationsInfo."+appNum+
^
SyntaxError: Unexpected token +
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
You need to set it the below way:
var appNum = 0;
var updateCon = {$set:{}};
updateCon.$set["applicationsInfo."+appNum+".consumerKey"] = 1;
Setting an expression ("applicationsInfo."+appNum+".consumerKey") as key of an object during initialization is not allowed in java script.

Exception when attempting to wrap Buffered-writer

Disclaimer: I'm fairly new to node (but not to JavaScript).
Im just trying to write a logger class, which holds a few lines at a time in memory, then flushes to disk when its buffer is reaching capacity
Problem
Calling my logger wrapper results in an exception in buffered writer
Im sure Ive misunderstood how require() works, and also various people advised me to create the object using new chatlogs.Chatlogger() but itI dont see many other node libs using this way of working
/www/im/node_modules/buffered-writer/lib/buffered-writer.js:125
cb ();
^
TypeError: undefined is not a function
at Writer.flush (/www/nodeim/node_modules/buffered-writer/lib/buffered-writer.js:125:3)
at Chatlogger.close (/www/nodeim/helpers/chatlogs.js:27:14)
at Object.<anonymous> (/www/nodeim/app.js:76:16)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
calling code...
var chatlogs = require('./helpers/chatlogs.js');
var chatlogger_obj = new chatlogs.Chatlogger();
chatlogger_obj.open("logs/log.txt");
chatlogger_obj.log("TESTING");
chatlogger_obj.close();
process.exit(0);
Wrapper class
./helpers/chatlogs.js
exports.version = '0.0.1';
var
buffer = require('buffered-writer'),
fs = require('fs');
var Chatlogger = function() {
this.handle = null,
this.filename = "",
this.dirtyops = 0;
}
Chatlogger.prototype.open = function (filename) {
//fs.unlink(filename);
this.filename = filename;
this.handle = buffer.open(filename)
.on ("error", function (error) {
//this.handle = null;
console.log (error);
});
}
Chatlogger.prototype.close = function() {
console.log("CLOSING");
this.handle.flush();
this.handle.close();
this.handle = null;
}
Chatlogger.prototype.log = function (str) {
console.log(str);
this.handle.writeln(str);
if (this.dirtyops++ > 5)
{
console.log("FLUSHING");
this.handle.flush();
this.dirtyops = 0;
}
}
module.exports.Chatlogger = Chatlogger;
I'm the author of this module. You need to pass a callback to the flush function, but you don't need to call to flush. When the buffered-writer closes or you exceed the buffer size when writing, the data is automatically flushed to disk.
Writer#flush(callback)

Resources