Issue in using google speech API with Node.js - node.js

I have used below code snippet for google speech to text recognition,
var speech = require('google-speech-api');
var opts = {
file: 'speech.mp3',
key: '<Google API Key>'
};
speech(opts, function (err, results) {
console.log(results);
// [{result: [{alternative: [{transcript: '...'}]}]}]
});
Then I tried to do
"npm install google-speech-api"
from command prompt. It's giving error.
Then, I did
"npm install googleapis"
and it succeeded.
I executed the Node.js script from command prompt "node myspeech.js"...it's throwing error as,
module.js:341
throw err;
^
Error: Cannot find module 'google-speech-api'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (C:\myspeechtest.js:1:76)
at Module._compile (module.js:413:34)
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)

As you can see in your error logs:
npm ERR! code ENOGIT
npm ERR! not found: git npm
ERR! npm ERR! Failed using git.
npm ERR! This is most likely not a problem with npm itself.
npm ERR! Please check if you have git installed and in your PATH.
You need to have git installed on your system, and in your PATH.
For Windows, you can use git-bash, for Debian/Ubuntu, a simple sudo apt-get install git should do the tricks.

const projectId = 'yourGoogleProjectId';
let file="conf.json"//google exported this for you
var speech = require('#google-cloud/speech')({
projectId: projectId,
keyFilename: file
});
const fs = require('fs');
const fileName = 'yourMp3FilePath';
// Reads a local audio file and converts it to base64
const fileMp3 = fs.readFileSync(fileName);
const audioBytes = fileMp3.toString('base64');
const audio = {
content:audioBytes
};
const config = {
encoding: 'AMR_WB',
sampleRateHertz: 16000,
languageCode: 'en-US'
};
const request = {
audio: audio,
config: config
};
speech.recognize(request)
.then((results) => {
const transcription = results[0].results[0].alternatives[0].transcript;
console.log(`Transcription: `, transcription);
})
.catch((err) => {
console.error('ERROR:', err);
});

Related

NodeJS - no such file or directory, scandir '/static/reports/'

I tried following this stackoverflow post to try and see my folder on my static webpage but no luck:https://stackoverflow.com/a/31274417
Here is my code:
const express = require('express');
const app = express();
const db = require('./persistence');
var fs = require('fs');
var files = fs.readdirSync('./static/reports');
app.use(require('body-parser').json());
app.use(express.static(__dirname + '/static'));
db.init().then(() => {
app.listen(3000, () => console.log('Listening on port 3000'));
}).catch((err) => {
console.error(err);
process.exit(1);
});
const gracefulShutdown = () => {
db.teardown()
.catch(() => {})
.then(() => process.exit());
};
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on('SIGUSR2', gracefulShutdown); // Sent by nodemon
Here is a picture of what it looks like from vscode:
Here is a picture of the error from docker:
Here is the error from text:
internal/fs/utils.js:269
throw err;
^
Error: ENOENT: no such file or directory, scandir './static/reports'
at Object.readdirSync (fs.js:955:3)
at Object.<anonymous> (/app/src/index.js:5:16)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47 {
errno: -2,
syscall: 'scandir',
code: 'ENOENT',
path: './static/reports'
}
Starting a file path with a / denotes that it's at the root of the filesystem. Don't use a /; instead, just use static/reports. You can also use ./static/reports if the code will be run from the src/ directory every time.
var fs = require('fs');
var files = fs.readdirSync('static/reports/');

EPERM error while trying to read fullchain.pem

I'm trying to host an HTTPS website with Node.js on my Windows 10 computer, but Node.js has suddenly stopped being able to read the fullchain.pem I obtained using Let's Encrypt's Certbot.
This is my Node.js code:
const fs = require("fs")
const https = require("https")
const FS_OPTIONS = {
encoding: "utf-8",
flag: "r",
}
const key = fs.readFileSync("C:/Certbot/live/subdomain.example.com/privkey.pem", FS_OPTIONS)
const cert = fs.readFileSync("C:/Certbot/live/subdomain.example.com/fullchain.pem", FS_OPTIONS)
https.createServer({ key, cert }, (req, res) => {
// do stuff...
}).listen(8888)
However, when I run it, I receive the following error:
Error: EPERM: operation not permitted, open 'C:/Certbot/live/subdomain.example.com/fullchain.pem'
at Object.openSync (fs.js:476:3)
at Object.readFileSync (fs.js:377:35)
at Object.<anonymous> (D:\Users\...\index.js:8:17)
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)
at internal/main/run_main_module.js:17:47 {
errno: -4048,
syscall: 'open',
code: 'EPERM',
path: 'C:/Certbot/live/subdomain.example.com/fullchain.pem'
}
The only way I can bypass this is by running as administrator, but this is very strange, as this was not required before.
How can I restore this to its previous behavior?
you just need to change the access rights of the folder and subfolders of : C:/Certbot
add access to the user running nodejs. for example following this :
https://v2cloud.com/tutorials/how-to-change-folder-permissions-on-windows-2016

npm ELIFECYCLE error with npm run start-server

I'm getting npm ERR! code ELIFECYCLE when I try to run my server command
What I'm trying to do is
TensorFlow.js Training in Node.js
It's for college, step 3 says to try out the server I get this
package.json snip
"scripts": {
"start-client": "webpack && webpack-dev-server",
"start-server": "node server.js"
},
error message
C:\xampp\htdocs\leo\baseball>npm run start-server
> tfjs-examples-baseball-node#0.2.0 start-server C:\xampp\htdocs\leo\baseball
> node server.js
internal/modules/cjs/loader.js:1122
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: Não foi possível encontrar o módulo especificado.
\\?\C:\xampp\htdocs\leo\baseball\node_modules\#tensorflow\tfjs-node\lib\napi-v5\tfjs_binding.node
at Object.Module._extensions..node (internal/modules/cjs/loader.js:1122:18)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\xampp\htdocs\leo\baseball\node_modules\#tensorflow\tfjs-node\dist\index.js:58:16)
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)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! tfjs-examples-baseball-node#0.2.0 start-server: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the tfjs-examples-baseball-node#0.2.0 start-server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Usuário\AppData\Roaming\npm-cache\_logs\2020-12-11T07_01_54_120Z-debug.log
server.js
require('#tensorflow/tfjs-node');
const http = require('http');
const socketio = require('socket.io');
const pitch_type = require('./pitch_type');
const TIMEOUT_BETWEEN_EPOCHS_MS = 500;
const PORT = 8001;
// util function to sleep for a given ms
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Main function to start server, perform model training, and emit stats via the socket connection
async function run() {
const port = process.env.PORT || PORT;
const server = http.createServer();
const io = socketio(server);
server.listen(port, () => {
console.log(` > Running socket on port: ${port}`);
});
io.on('connection', (socket) => {
socket.on('predictSample', async (sample) => {
io.emit('predictResult', await pitch_type.predictSample(sample));
});
});
let numTrainingIterations = 10;
for (var i = 0; i < numTrainingIterations; i++) {
console.log(`Training iteration : ${i+1} / ${numTrainingIterations}`);
await pitch_type.model.fitDataset(pitch_type.trainingData, {epochs: 1});
console.log('accuracyPerClass', await pitch_type.evaluate(true));
await sleep(TIMEOUT_BETWEEN_EPOCHS_MS);
}
io.emit('trainingComplete', true);
}
run();
I already tried:
cache clean --force/-f, delete node_modules package-lock.json run npm install
removing package-lock.json and running the server
npm install -g node-pre-gyp
npm install --unsafe-perm
Changing the port from 8001 to 10000 3000 80
running it with every single thing else on my computer closed (this includes my xampp on the bg)
some info
node -v 14.15.1
npm -v 6.14.8
windows 10 x64
My grade needs me to overcome this and finish the tutorial
line 13 of my error accused something wrong at line 58 at this file
at Object.<anonymous> (C:\xampp\htdocs\leo\baseball\node_modules\#tensorflow\tfjs-node\dist\index.js:58:16)
opened the file and commented the line, code ran without problems

How to solve this 'SyntaxError: Invalid regular expression: /^function authenticate(req, res, next)'?

I'm working on backend (Express, Node, Mongo). I set up https with OpenSSL and as required I made changes into bin/www and in app.js. I'm geting very unfamiliar error and very long error. I'm including it here.
E:\CourseraMERN\NodeJS\conFusionServer\node_modules\path-to-regexp\index.js:128
return new RegExp(path, flags);
^
SyntaxError: Invalid regular expression: /^function authenticate(req, res, next) {
if (http\.IncomingMessage\.prototype\.logIn
&& http\.IncomingMessage\.prototype\.logIn !== IncomingMessageExt\.logIn) {
require('\.\.\/framework\/connect')\.__monkeypatchNode();
}
\/\/ accumulator for failures from each strategy in the chain
var failures = [];
function allFailed() {
if (callback) {
if (!multi) {
return callback(null, false, failures[0]\.challenge, failures[0]\.status);
} else {
var challenges = failures\.map(function(f) { return f\.challenge; });
var statuses = failures\.map(function(f) { return f\.status; });
return callback(null, false, challenges, statuses);
}
}
..................................................................
..................................................................
..................................................................
at new RegExp (<anonymous>)
at pathtoRegexp (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\path-to-regexp\index.js:128:10)
at new Layer (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\layer.js:45:17)
at Function.route (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\index.js:494:15)
at Function.proto.<computed> [as get] (E:\CourseraMERN\NodeJS\conFusionServer\node_modules\express\lib\router\index.js:509:22)
**at Object.<anonymous> (E:\CourseraMERN\NodeJS\conFusionServer\routes\users.js:12:8)**
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
**at Object.<anonymous> (E:\CourseraMERN\NodeJS\conFusionServer\app.js:13:19)**
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! confusionserver#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the confusionserver#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Lenovo\AppData\Roaming\npm-cache\_logs\2020-09-07T04_31_33_225Z-debug.log
users.js line 12:
router.get( authenticate.verifyUser, authenticate.verifyAdmin, '/', function(req, res, next) {
User.find({})
.then((users) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(users);
}, (err) => next(err))
.catch((err) => next(err));
});
app.js line 13:
var usersRouter = require('./routes/users');
So, where am I missing? Why I'm getting that error? Before changing the code for OpenSSL everything was working fine and now this.
My Node version is: v12.18.1, express: 4.16.1, npm: 6.14.8
The path argument for router.get() has to come first.
Change this:
router.get( authenticate.verifyUser, authenticate.verifyAdmin, '/', ...)
to this:
router.get('/', authenticate.verifyUser, authenticate.verifyAdmin, ...)
The error is attempting to show that you're passing authenticate.verifyUser where Express expects either a string or a regex, but you're passing a function.
FYI, this is an interesting example for where TypeScript could be helpful. This could have been a compile error about a wrong argument type for the first argument, instead of a cryptic run-time error.
From the Express doc, the signature for app.get() is this:
app.get(path, callback [, callback ...])
The path must be first followed by one or more callbacks.

karma start throwing useragent error

I generated an app using yeoman by doing this in a folder called sw-front:
yo angular
I installed karma like this
npm install -g karma
npm install -g karma-cli
grunt serve works fine.
karma -v throws the same error:
mm-mac-2186:sw-front pkatepalli$ karma start
module.js:340
throw err;
^
Error: Cannot find module 'useragent'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/pkatepalli/Desktop/hands-on-angular/sw-front/node_modules/karma/lib/helper.js:4:17)
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)
module.js:
var Module = function() {
var providers = [];
this.factory = function(name, factory) {
providers.push([name, 'factory', factory]);
return this;
};
this.value = function(name, value) {
providers.push([name, 'value', value]);
return this;
};
this.type = function(name, type) {
providers.push([name, 'type', type]);
return this;
};
this.forEach = function(iterator) {
providers.forEach(iterator);
};
};
module.exports = Module;
mm-mac-2186:sw-front pkatepalli$ node -v
v0.10.28
mm-mac-2186:sw-front pkatepalli$ npm -v
1.4.9
Try
npm cache clean
And removing the node_modules directory, if it exists, where you are running the commands form.
Then rebuild/reinstall

Resources