Nodejs, Electron nightmare is not defined when it's installed? - node.js

I've installed Nightmare via NPM this is my code:
var jquery = require('jquery')
var nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
$( "#test" ).addEventListener('click',() => {
nightmare
.goto('http://akhiljose.me/master/paste/')
.type('.form-control', 'Test')
.type('input[type=test]', 'nightmare_test')
.click('input[type=submit]')
.wait(7000)
.evaluate(function () {
return document.querySelector('pre').innerText;
})
.end()
.then(function (result) {
console.log(result);
})
.cat(function (error) {
console.error('Search failed:', error);
})});
However console logs:
C:\Users\ninja_000\Desktop\clu-gen\index.js:3 Uncaught ReferenceError: Nightmare is not defined
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:3:17)
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:22:3)
at Module._compile (module.js:642:30)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:504:12)
at Function.Module._load (module.js:496:3)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at file:///C:/Users/ninja_000/Desktop/clu-gen/index.html:12:5
I'm very new to nodejs what is causing this error? Am I do something wrong?

You are calling an undefined variable.
var jquery = require('jquery')
var nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
The second line declares a variable nightmare but the next line you are calling Nightmare. Make the second line uppercase.
var jquery = require('jquery')
var Nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
You can see from the second line of the stack trace:
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:3:17)
Line 3:17, there is an uncaught ReferenceError: Nightmare. This make sense because Nightmare is not defined, so nodejs cannot find it. The line numbers in the stack trace are useful to pinpoint where in the code the error is occurring. You can also use a linter which will show an error for trying to use an undefined variable. Something like eslint.

Should've defined as Nightmare not nightmare

Related

Issue with module wrapper function

I'm trying to learn node.js, and having an issue with running a code with module wrapper function. Here is the code
logger.js (1)
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
module.exports.log = log;
logger.js(2)
( function (exports, require, module, __filename, __dirname)
{
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
module.exports.log = log;
})
app.js
const logger = require('./logger.js')
console.log(logger);
logger.log('Hiya');
The logger.js(1) works fine, logger.js(2) gives out following error.
TypeError: logger.log is not a function
at Object.<anonymous> ()
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
I was expecting to get the same result from both cases
In the snippet which you have attached as logger.js(2),
function (exports, require, module, __filename, __dirname) is irrelevant and does not make sense to the NodeJS Compiler.
The correct way of doing what you expect is the one listed in logger.js(1)
If you are exporting multiple functions then,
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
function log_twice(message) {
console.log(message);
console.log(message);
}
module.exports = { log: log, log_twice: log_twice }; //and so on
Request to accept the answer if it helps...

TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function puppeteer node js

I am stuck here for a while I didn't understand the problem. Kindly someone enlightens me on this topic. here's the code.
const puppeteer = require('puppeteer');
(async() => {
let infourl = 'https://www.imdb.com/title/tt0111161/?ref_=fn_al_tt_3';
let browser = await puppeteer.launch();
let page = await browser.newPage();
await page.goto(infourl, { waitUntil:'networkidle2' });
let data = await page.evaluate( () =>{
let stats = document.querySelector('div[class="title_wrapper"]').innerText;
return {stats};
});
console.log(data);
debugger;
await browser.close();
})();
here is the log::
internal/util.js:209
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'original', 'function');
^
TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function
at promisify (internal/util.js:209:11)
at Object.<anonymous> (/home/hadi/Desktop/datachori/node_modules/extract-zip/index.js:11:18)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/home/hadi/Desktop/datachori/node_modules/puppeteer/lib/BrowserFetcher.js:25:20)
It occurred to the latest version of puppeteer.
Your scripts will work properly in the lower version.
Try this script:
npm i -save puppeteer#1.7.0
Execute the following commands
npm config set PUPPETEER_SKIP_CHROMIUM_DOWNLOAD false
npm config set ignore-scripts false
then:
npm config set ignore-scripts true
change the flag for the ignore-scripts back as it poses a security threat if left false

node.js then() not working

I am new to node.js so I am trying to understand promises and wait on node.js. I want to print the file note.txt.
Here is my code
var fs = require('fs');
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
When I run above code. I get the following error.
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
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
And I try another method for the same thing.
var fs = require('fs');
async function read_file(){
var file_data = await fs.readFile('note.txt','utf8');
return file_data;
}
console.log(read_file());
And I get following error
Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
I get the same error when I run with --harmony. I m not sure if there is bug on my code or what is wrong. Please help me understand.
My Environment
Node version: v8.9.0
node -p process.versions.v8: 6.1.534.46
You're getting errors because fs.readfile doesn't return a promise; hence then doesn't exist. For you to use the function as a promise, you will need to wrap it up as a promise; you could use something like bluebird or Q.
Thank you for the answers. I learned that function must return promise in order to use then() and catch(). So the code should be like this
var fs = require('fs');
function read_file(){
return new Promise(function(resolve, reject) {
fs.readFile('note.txt','utf8',function(err,file){
if(err){
return reject(err);
}else{
resolve(file);
}
});
});
}
read_file().then(
(data)=>{
console.log('success: '+data);
}
).catch((err)=>{
console.log('error: ',err);
});
If you use NodeJs v10, try fs.promises:
var fs = require('fs').promises; // v10.0 use require('fs/promises')
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
If not, use readFileSync:
// This code can use for node v10 or lowwer
var fs = require('fs');
var data = fs.readFileSync('a.json');
console.log(data);
try to use the async await
function (async err => {
if (err) {
console.err ....}
await .... <other function included or comes after then .>
await ... <other function included>
})

AssertionError: path must be a string

require([
'common',
// Libs
'jquery',
'parse',
'i18n',
// Modules
'modules/login/controllers/login',
'modules/page/controllers/page',
// Styles
'css!../assets/css/bootstrap.min.css',
'css!../assets/css/tablesorter-bootstrap-theme.css',
'css!../assets/css/common.css',
],
function(common, $, Parse, i18n, Login, Page) {
// Defining the application router, you can attach sub routers here.
var Router = Parse.Router.extend({
routes : {
'' : 'index'
},
index : function() {
var currentUser = Parse.User.current(),
view, container;
// Load either login screen or navigation bar,
// depending on the login state of current user.
if(currentUser){
view = new Page.Views.Navbar();
container = '#navbar';
} else {
view = new Login.Views.Login();
container = '#main';
$('#navbar').html(null); // Remove the navbar
}
view.render(function(el) {
$(container).html(el);
});
}
});
$(function() {
// Initialize internationalization
i18n.init({
saveMissing: true,
debug: true,
//preload: ['dk', 'en'],
getAsync: false
});
Parse.initialize('****','****');
// Initialize the Router
var router = new Router();
Parse.history.start({ pushState: false });
});
$(document).on( 'click', 'a:not([data-bypass])', function(evt) {
// Get the anchor href and protcol
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href && href.slice(0, protocol.length) !== protocol && href.indexOf('javascript:') !== 0) {
evt.preventDefault();
Parse.history.navigate(href, { trigger: true });
}
});
});
Got error:
assert.js:85
throw new assert.AssertionError({
^
AssertionError: path must be a string
at Module.require (module.js:482:3)
at require (internal/module.js:20:19)
at Object. (/home/historiejagt.portaplay.dk/public_html/app/app.js:4:1)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
Read the error:
AssertionError: path must be a string
at Module.require (module.js:482:3)
at require (internal/module.js:20:19)
at Object. (/home/historiejagt.portaplay.dk/public_html/app/app.js:4:1)
Look at your code:
require([
An array is not a string.
I think I worked out what's going on, though it would have been a lot easier if someone had been more specific about where they're copy-pasting code from.
The function require(array, callback) is part of RequireJS. NodeJS doesn't use that and has require(string) instead. If you want to use RequireJS in NodeJS you need to install and require requirejs first.

Replacing karma with jasmine-node for my AngularJS tests?

Jasmine AngularJS test (passes in karma start configs/karma.conf.js)
describe('IndexController', function () {
beforeEach(module('myApp'));
var ctrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('IndexController', {
$scope: scope
});
}));
it('should add name parameter to scope', function () {
expect(scope.name).toBeDefined();
});
});
Contents of controllers.js
var myApp = angular.module('myApp', []);
myApp.controller('IndexController', function ($scope) {
$scope.name = 'bob';
});
Output of: jasmine-node test/ --junitreport
Message:
TypeError: object is not a function
Stacktrace:
TypeError: object is not a function
at null.<anonymous> (/tmp/tests/test/unit/controllerSpec.js:38:16)
at Object.<anonymous> (/tmp/tests/test/unit/controllerSpec.js:36:1)
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 Module.require (module.js:364:17)
at require (module.js:380:17)
beforeEach() taks in a function. Be sure module('myApp') and inject(...) are returning actual function definitions. Jasmine's beforeEach is like "call the passed function before each test", so you may want:
beforeEach( function(){ module('myApp') } );
I am unfamiliar with karma, but do use jasmine's done() method in my beforeEach() like this:
var valueForEachTest = null;
beforeEach( function(done) {
doSomething( function(value){
valueForEachTest = value;
done();
});
} );
Not using that done() call breaks my tests because I'm doing a few asynchronous call in there (perhaps Jasmine is not waiting for beforeEach to finish?).
Angular is made to run in the browser. It will not run in node. At least, not without a lot of effort.
There has been an attempt to port it to node, but that project is really intended to render angular pages server side for search engine optimization. Unless you have a really good reason, you shouldn't be trying to test Angular apps in Node.

Resources