'use-strict' enabled but not working in node - node.js

I have enabled use-strict mode in my .js file but when I run it, node keeps telling me that I don't have it enabled. PLEASE don't tell me to write "use-strict"; at the top of my file because I already tried that.
Here is my server.js file. I have been trying to see what is wrong but so far stack overflow has not been much help since most people seem to get this working on their first try.
require('use-strict')
'use-strict';
let util = require('util');
let http = require('http');
let Bot = require('#kikinteractive/kik');
var kik_username = process.env.KIK_USERNAME;
var kik_api_key = process.env.KIK_API_KEY;
var kik_baseUrl = process.env.KIK_BASEURL;
// Configure the bot API endpoint, details for your bot
let bot = new Bot({
username: kik_username,
apiKey: kik_api_key,
baseUrl: kik_baseUrl
});
bot.updateBotConfiguration();
bot.onTextMessage((message) => {
message.reply(message.body);
});
// Set up your server and start listening
let server = http.createServer(bot.incoming()).listen(8085);
Everything seems fine but when I run
$ node server.js
I keep getting this error
let util = require('util');
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:148:18)
at node.js:405:3
It tells me to enable strict mode BUT I ALREADY DID THAT. I even required an npm package to make sure I was doing it right! Can anyone make sense of what is happening?

No dash in 'use strict'
'use strict' // not 'use-strict'
Check out the documentation for further reference

You don't need to require an npm package. just put "use strict"; at the top of the js file.

Related

Read file and write file JSON

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]);

Reference a global JS function in another file, in NodeJS

What I'm actually doing is writing a VS Code Extension, but since I'm new to Node I'm struggling with referencing one JS file from another.
//main.js (compiled from TypeScript)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("./Test.js");
console.log("hello");
t1();
and
//Test.js
function t1() {
console.log("t1");
}
They're both in the same folder. If I run it from VS Code, or from node directly, it doesn't work
PS E:\VSCodeTest> node src/main.js
hello
E:\VSCodeTest\src\main.js:5
t1();
^
ReferenceError: t1 is not defined
at Object.<anonymous> (E:\VSCodeTest\src\main.js:5:1)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
The VS Code project is actually TypeScript but I've distilled it down to the crux of the problem in the JS files.
I believe it should work based on
https://www.typescriptlang.org/docs/handbook/modules.html
Import a module for side-effects only Though not recommended practice,
some modules set up some global state that can be used by other
modules. These modules may not have any exports, or the consumer is
not interested in any of their exports. To import these modules, use:
import "./my-module.js";
How have I misunderstood that?
Change Test.js to this:
//Test.js
function t1() {
console.log("t1");
}
module.exports = t1;
And then do something more like this in main.js:
const t1 = require("./Test.js");
t1(); // prints "t1"
There's a lot of information about how modules work in the docs: https://nodejs.org/api/modules.html
Alternatively, if you want t1 to be a global, then assign it to global.t1 in Test.js:
//Test.js
global.t1 = function t1() {
console.log("t1");
};
I wouldn't recommend that if you can avoid it, though, for all the reasons people recommend avoiding globals when possible
Require doesn't work quite like that, but you're close -- if you want to use a function you've created to in another file, just add it to that file's exports.
/// test.js
exports.t1 = function() ...
// or
module.exports = {
t1: function() ...
}
Then you need to specifically save that off to use it
/// main.js
var t1 = require('./test.js').t1;
t1();
Global scoping doesn't work like it does in the browser, check out node's docs on it, or try a blog explaining it (I didn't write this and can't fully vouch)

In Node, how do I elegantly handle requiring modules that read files in their directories?

For instance, in my project directory, I have:
|--bar.js
|--dir
|--foo.txt
|--readfile.js
readfile.js:
const fs = require('fs');
var foo = fs.readFileSync('foo.txt', 'utf8');
console.log(foo);
module.exports = {foo};
Running node readfile.js, everything works perfectly.
bar.js:
const readfile = require('./dir/readfile');
console.log(read.foo);
Running node bar.js, I get:
fs.js:663
return binding.open(pathModule.toNamespacedPath(path),
^
Error: ENOENT: no such file or directory, open 'foo.txt'
at Object.fs.openSync (fs.js:663:18)
at Object.fs.readFileSync (fs.js:568:33)
at Object.<anonymous> (/Users/fterh/Documents/Projects/playground/dir/readfile.js:3:14)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
Fabians-MacBook-Pro:playground fterh$
I know it has to do with require('./dir/readfile') in bar.js, because Node then tries to search for "foo.txt" in the same directory as "bar.js". Currently, my fix is to use path.dirname(__filename) to get absolute paths, which would work regardless of whether I'm running the module directory or requiring it. I'm wondering if there is a more elegant way of doing things.
Use of require.resolve within readfile.js as follows:
const fs = require('fs');
let foo = fs.readFileSync(require.resolve('./foo.txt'), 'utf8');
console.log(foo);
module.exports = {foo};
Note: in the original question for bar.js it may have been intended to write: console.log(readfile.foo);.
require.resolve:
... return the resolved filename
Use __dirname to construct your path as that will always point to the directory where your module was loaded from, regardless of the current directory. This is one of the variables that is passed into a module so it has a unique value in the scope of each module and it's purpose is for exactly what you want (to do file operations relative to your module's directory).
const fs = require('fs');
const path = require('path');
var foo = fs.readFileSync(path.join(__dirname, 'foo.txt'), 'utf8');
console.log(foo);
module.exports = {foo};
Reference info for __dirname here.

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');
});

Unexpected token =

I'm unsure as to what could cause this error in Node.js, as I've never seen it before and cannot find another issue online.
Message:
Unexpected token =
Stack:
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (/Projects/api/test/integration/models/article.js:3:15)
The file that is causing the error has the following contents:
'use strict';
var Article = require('../../../models/article')
Why in the world would = cause an error?
Edit 1 - adding the article.js that is being required:
'use strict';
class ArticleModel {
constructor(options = {}) {
this.options = options
}
}
module.exports = ArticleModel
node.js 5.0 does not support all ES6 features yet. In particular, it does not yet support default parameters.
So this line:
constructor(options = {}) {
is what is causing the error with the = assignment.
See this table for which features are supported in node.js 5.0.
You can replace the default parameter assignment with the old fashioned method:
constructor(options) {
this.options = options || {};
}
I think, your current Node.js distribution doesn't support default parameter values.
You should remove it:
constructor(options) {
this.options = options || {};
}
Or, try to play with --harmony runtime flag.
According to this link --harmony can not to help, this feature doesn't implemented in node5.0 at all.
I am using Node v5.7.0 and can enable default parameters using this option:
--harmony-default-parameters
The error is on the 3rd line of article.js.

Resources