NPM and NodeJS Compatibility: NodeJS works from PM prompt, but not script - node.js

I am attempting to get a lighthouse script running in Node.JS (which I am new to). I followed the intial instructions here https://github.com/GoogleChrome/lighthouse/blob/master/docs/readme.md#using-programmatically. I was able to complete the prior steps in the package manager console (Visual Studio 2017):
npm install -g lighthouse
lighthouse https://airhorner.com/
//and
lighthouse https://airhorner.com/ --output=json --output-path=./report/test1.json
However, I do get an initial warning that NPM only supports Node.JS in versions 4 through 8 and recommends a newer version. The problem is I am running Node v12 and NPM v5 - both the latest.
When I create a script version like below (app.js)
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const config = {
extends: 'lighthouse:default',
settings: {
emulatedFormFactor: 'desktop',
onlyCategories: 'performance',
output: 'json',
outputPath: './report.json'
}
};
function launchChromeAndRunLighthouse(url, opts = null, config) {
return chromeLauncher.launch().then(chrome => {
opts.port = chrome.port;
return lighthouse(url, opts, config).then(results => {
return chrome.kill().then(() => results.lhr);
});
});
}
// Usage:
launchChromeAndRunLighthouse('https://airhorner.com/', config).then(results => {
// Use results!
});
And run the command
C:\src\project> node app.js
I get the error - Cannot find module 'lighthouse'

don't install lighthouse locally use it inside your working dir .
first start by running npm init that will create the package.json file inside the current working dir
then npm install --save lighthouse will download it and save it to node_modules now you can use it locally inside your working dir
it should look something like this
app.js
package.json
node_modules/
then run node app.js

Related

Vue Error - Can't resolve 'https' when importing package

I'm trying to make a Vue project and use an npm package for connecting to the retroachievements.org api to fetch some data, but I'm getting an error. Here's my process from start to finish to create the project and implement the package.
Navigate to my projects folder and use the vue cli to create the project: vue create test. For options, I usually chose not to include the linter, vue version 2, and put everything in package.json.
cd into the /test folder: cd test and install the retroachievements npm package: npm install --save raapijs
Modify App.vue to the following (apologies for code formatting, not sure why the post isn't formatting/coloring it all properly...):
const RaApi = require('raapijs');
export default {
name: 'App',
data: () => ({
api:null,
user: '<USER_NAME>',
apiKey: '<API_KEY>',
}),
created() {
this.api = new RaApi(this.user, this.apiKey);
},
}
run `npm run serve' and get the error:
ERROR in ./node_modules/raapijs/index.js 2:14-30
Module not found: Error: Can't resolve 'https' in 'C:\Projects\Web\test\node_modules\raapijs'
I'm on Windows 10, Node 16.17.0, npm 8.15.0, vue 2.6.14, vue CLI 5.0.8, raapijs 0.1.2.
The first solution below says he can run it without error but it looks like the exact same code as I'm trying. Can anyone see a difference and a reason for this error?
EDIT: I reworded this post to be more clear about my process and provide more info, like the versions.
This solution works for me. I installed raapijs with npm install --save raapijs command. Then in my Vue version 2 component I used your code as follow:
const RaApi = require('raapijs');
export default {
data: () => ({
api: null,
user: '<USER_NAME>',
apiKey: '<API_KEY>',
}),
created() {
this.api = new RaApi(this.user, this.apiKey);
},
};
It seems the raapijs package was designed to be used in a Node environment, rather than in Vue's browser based environment, so that's the reason I was getting an error. The package itself was looking for the built in https package in Node, but since it wasn't running in Node, it wasn't finding it.
So I solved my problem by looking at the package's github repo and extractingt he actual php API endpoints that were being used and using those in my app directly, rather than using the package wrapper. Not quite as clean and tidy as I was hoping but still a decent solution.

Selenium on a Docker container

I have a simple javascript file that uses selenium to launch Chrome, open some website, and collect some data from that website. Now, I want to put that file and run it inside a Docker container.
To do this I wrote the following Dockerfile:
FROM alpine
RUN apk add --update nodejs npm chromium
COPY . /src
WORKDIR /src
RUN npm install -g chromedriver
RUN npm install
ENTRYPOINT ["node", "index.js"]
The image builds with no errors, but when I attempt to run the container from it I get:
/src/node_modules/selenium-webdriver/remote/index.js:248
reject(Error(e.message))
^
Error: Server terminated early with status 1
at /src/node_modules/selenium-webdriver/remote/index.js:248:24
at processTicksAndRejections (node:internal/process/task_queues:96:5)
There's only one dependency for my index.js file - "selenium-webdriver": "^4.1.1", and the file itself looks like this:
index.js
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.example.com');
// Get all the elements available with tag 'p'
let elements = await driver.findElements(By.css('p'));
for(let e of elements) {
console.log(await e.getText());
}
}
finally {
await driver.quit();
}
})();
What am I doing wrong? How can I make the container run successfully?
I think the problem is with selenium-webdriver/chrome,
since the builder is getting stuck on mine.

How to run electron on a localhost server in Build as well as in Dev

I'm developing with Next.js + Electron + Typescript.
I'm using the npx create-next-app --example with-electron-typescript command to generate code.
npm run dev (the contents are npm run build-electron && electron . ), it seems that the local server is up and running on localhost8000, but when build, the server is not up internally, and it is running by directly accessing the file.
However, some APIs do not work correctly if there is no domain in the location.origin , so it works in Dev, but does not work in Build.
So, if it is possible, I would like to run the server on localhost in the build version as well as in the Dev version.
Is there anything I can do to make it work?
It's not shown in any of the examples, even though someone requested one:
https://github.com/vercel/next.js/issues/28225
It is possible using a custom server:
https://nextjs.org/docs/advanced-features/custom-server
You can follow these steps to create one:
Clone the Electron Next TypeScript example repo:
https://github.com/vercel/next.js/tree/canary/examples/with-electron-typescript
Update ./electron-src/index.ts with the following code:
import isDev from 'electron-is-dev';
import { createServer } from 'http';
import next from 'next';
import { parse } from 'url';
app.on('ready', async () => {
// Use server-side rendering for both dev and production builds
const nextApp = next({
dev: isDev,
dir: app.getAppPath() + '/renderer'
});
const requestHandler = nextApp.getRequestHandler();
// Build the renderer code and watch the files
await nextApp.prepare();
// Create a new native HTTP server (which supports hot code reloading)
createServer((req: any, res: any) => {
const parsedUrl = parse(req.url, true)
requestHandler(req, res, parsedUrl)
}).listen(3000, () => {
console.log('> Ready on http://localhost:3000')
})
mainWindow.loadURL('http://localhost:3000/')
Update ./package.json Electron build configuration to include the renderer src files:
"build": {
"asar": true,
"files": [
"main",
"renderer"
]
}
In ./package.json move next from devDependencies to dependencies. This means it will be available to run in production builds
Then use helpful scripts to unpack the binary and see the files/folder inside:
npx asar extract ./dist/mac/ElectronTypescriptNext.app/Contents/Resources/app.asar ./dist/unpack
Run the unpacked version to debug:
./node_modules/.bin/electron ./dist/unpack
I have created an Express Server version and NextJS versions to prove it is possible:
https://github.com/kmturley/electron-server/tree/feature/express
https://github.com/kmturley/electron-server/tree/feature/next

Suddenly started encountering Internal Server Error 500 on Mac for React App with Express server

In my react app I have an API that I am calling from my redux-saga. I am using express for my server. The code has been hosted and is working just fine. But today, I deleted the build directory and reran npm run build and then npm start and started getting this error on my local Mac.
Error on Chrome:
The error in index.js expanded if it helps:
Error on Safari:
I am pretty sure my code is proper as it has been running just fine for months now and I have made no major changes right now expect adding some console.log statements.
My API in Express Server:
app.get("/api/getProblems", (req, res) => {
var sheetKey = SECRET_KEY;
tabletop.init({
key: sheetKey,
callback: (sheet) => {
res.json(sheet);
console.log("Sent list of problems");
},
simpleSheet: true,
});
});
Calling from Saga:
function* fetchProblems() {
const data = yield call(() =>
fetch("/api/getProblems")
.then(response => response.json())
.then(sheet => sheet)
);
//Rest of the logic
}
For a brief moment I was seeing the following error:
Could not proxy request /api/getProblems from localhost:3000 to http://localhost:8000 (ECONNREFUSED)
But then it was replaced by the above error.
It was my mistake in starting the server. I ran npm start in the wrong folder. From the root I had to run the following commands:
cd client; npm run build; cd ..; npm start;

Sails.js + apidocjs + grunt - auto generate documentation

I'm new to Sails.js and Node.js and I have problems with creating documentation for my application.
Here's my steps:
installed apidoc by:
npm install apidoc -g
installed grunt module:
npm install grunt-apidoc --save-dev
added grunt.loadNpmTasks('grunt-apidoc'); to Gruntfile.js at the bottom
created grunt.initConfig file and put:
apidoc: {
myapp: {
src: "api/controllers/",
dest: "apidoc/"
}
}
Then I'm trying to run multiple things, and none of them produces my api documentation:
sails lift
grunt
grunt default
node app.js
If I run it manually by apidoc -i api/controllers/ -o apidoc/ it's working properly.
What am I doing wrong? How to do it?
Super late answer!
From my experience modifying the asset pipeline you'd be better off:
Install apidoc and the Grunt module as in the Question
Create a new file in `tasks/config/apidoc.js:
module.exports = function (grunt) {
grunt.config.set('apidoc', {
myapp: {
src: "api/controllers/",
dest: "apidoc/"
}
});
grunt.loadNpmTasks('grunt-apidoc');
};
Edit tasks/register/compileAssets.js (or wherever you want the task to be run):
module.exports = function (grunt) {
grunt.registerTask('compileAssets', [
'clean:dev',
'jst:dev',
'less:dev',
'copy:dev',
'coffee:dev',
'apidoc:myapp' // <-- This will now run every time your assets are compiled
]);
};
Hope this helps someone

Resources