Metadata of ffmpeg is undefined in electron app - javascript

I correctly installed ffmpeg I'm able to check it by writing ffmpeg in cmd which give me this result
Now in my electron app in my index.html I'm geting input from user and sending custom event to electron side of app which lays in index.js entry point
index.html
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
const { path } = document.querySelector('input').files[0];
ipcRenderer.send('video:submit', path);
});
</script>
and using ffmpeg.ffprobe I'm trying to get metadata of video updated to input in electron side like so:
const electron = require('electron');
const ffmpeg = require('fluent-ffmpeg');
const { app, BrowserWindow, ipcMain } = electron;
app.on('ready', () => {
const mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}/index.html`);
});
ipcMain.on('video:submit', (event, path) => {
ffmpeg.ffprobe(path, (err, metadata) => {
console.log(metadata);
//console.log(metadata.format.duration);
});
});
And it console that metadata is undefined, when I uncomment console.log(metadata.format.duration) it says
typeError: cannot read property
'format' of undefined
What I'm doing wrong?
So I set two new environment variables and now other error occure when I console.log(error):
{ Error: spawn C:\Users\Borys\Documents\videoinfo\ffmpeg\bin ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn C:\\Users\\Borys\\Documents\\videoinfo\\ffmpeg\\bin',
path: 'C:\\Users\\Borys\\Documents\\videoinfo\\ffmpeg\\bin',
spawnargs:
[ '-show_streams',
'-show_format',
'C:\\Users\\Borys\\Documents\\portfolio\\img\\header_video.mp4' ] }`
( I had to paste it as code because it was saying that my post containt code that is not properly formatted)

Alright thanks to #Alexander Leithner and this question I figured it out. So error was my environment variables which should be:
FFMPEG_PATH with value of path to ffmeg.exe
FFPROBE_PATH with value of path to ffprobe.exe
PATH with value of C:.......\ffmpeg\bin

Related

Why does the yarn command report an error when executing my script

const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const root = __dirname;
function createSpawn(command, next) {
const child = spawn(command, {
stdio: 'inherit',
shell: true,
cwd: root,
});
child.on('exit', function () {
if (typeof next === 'function') {
next();
}
});
}
function install() {
fs.rmSync(path.resolve(root, '.husky'), {
recursive: true,
force: true,
});
createSpawn('npx husky install', () => {
createSpawn('npx husky add .husky/pre-commit "npm run pre-commit"', () => {
createSpawn('npx husky add .husky/commit-msg "npx --no -- commitlint --edit #EE#"', () => {
const file = path.resolve(root, '.husky/commit-msg');
let content = fs.readFileSync(file).toString();
content = content.replace('#EE#', '"$1"');
fs.writeFileSync(file, content);
});
});
});
}
install();
I test on windows, and it work fine
I used the yarn command to install dependencies, but an error occurred. It was still good before. I suspect that the permissions of the husky file are incorrect, but an error is reported in the yarn script
but when i use the commnad node install.js it work fine!!!
here is the error
yarn install v1.22.19
[1/4] 🔍 Resolving packages...
success Already up-to-date.
$ node install.js
node:internal/fs/utils:344
throw err;
^
Error: ENOENT: no such file or directory, open '/Users/ao/Desktop/Yeastar/PPV3/ppfe/.husky/commit-msg'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at /Users/ao/Desktop/Yeastar/PPV3/ppfe/install.js:32:34
at ChildProcess.<anonymous> (/Users/ao/Desktop/Yeastar/PPV3/ppfe/install.js:17:13)
at ChildProcess.emit (node:events:526:28)
at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/Users/ao/Desktop/Yeastar/PPV3/ppfe/.husky/commit-msg'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

NodeJS Write and Read simple file from lambda

I can't find any issue with my code. Why I can't write the file and read the file? Is there a better way to create the file so I can upload it to S3?
const fs = require('fs');
const {
format
} = require('#fast-csv/format');
const filePath = '/tmp/myFile.csv';
const file = fs.createWriteStream(filePath);
const stream = format({
headers: headers
});
stream.pipe(file);
writeEmissionsToCsv(stream, cars);
stream.end();
console.log("File created!");
uploadToS3(fs.readFileSync(filePath)) // Error here!!
const writeToCSV = (stream, cars) => {
cars.forEach((car) => {
stream.write([
model: car.model
]);
});
}
log:
File created!
Error: ENOENT: no such file or directory, open
'/tmp/myFile.csv'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at Runtime.lambdaHandler [as handler] (/var/task/app.js:86:27)
at processTicksAndRejections (node:internal/process/task_queues:96:5) { errno: -2, syscall:
'open', code: 'ENOENT', path: '/tmp/myFile.csv' }

GCS catch error if file not found in bucket while streaming download

I am trying to fetch images from google cloud storage bucket from browser and serving the files using API in express. Following code breaks when the Image path is invalid. The try catch doesn't catch the file not found error. Am I missing something here? This code works if an image file exists.
From the Express side, I am using wildcard route (i.e. /*) as the API can accept any image path coming in and try to serve it.
const express = require('express')
const {Storage} = require('#google-cloud/storage');
let server = express()
const storage = new Storage();
const bucketName = '<some-bucket-name>'
server.get('/*', async (req, res) => {
const widthString = req.query.width
const heightString = req.query.height
const format = req.query.format
const fileName = req.path.substring(1);
console.log("url: ", req.path)
let width, height
if (widthString) {
width = parseInt(widthString)
}
if (heightString) {
height = parseInt(heightString)
}
res.type(`image/${format || 'png'}`)
try{
await storage.bucket(bucketName).file(fileName).createReadStream().pipe(res)
} catch (err) {
console.error(err);
}
})
Error:
url: /media/artist/banner_image/16118/screenshot_2019_12_16_at_10.35.24_am.png
events.js:377
throw er; // Unhandled 'error' event
^
ApiError: No such object: assets/media/artist/banner_image/16118/screenshot_2019_12_16_at_10.35.24_am.png
at new ApiError (/home/ubuntu/imageoptimizer/node_modules/#google-cloud/common/build/src/util.js:73:15)
at Util.parseHttpRespMessage (/home/ubuntu/imageoptimizer/node_modules/#google-cloud/common/build/src/util.js:175:41)
at Util.handleResp (/home/ubuntu/imageoptimizer/node_modules/#google-cloud/common/build/src/util.js:149:76)
at Duplexify.<anonymous> (/home/ubuntu/imageoptimizer/node_modules/#google-cloud/storage/build/src/file.js:888:31)
at Duplexify.emit (events.js:400:28)
at PassThrough.emit (events.js:400:28)
at onResponse (/home/ubuntu/imageoptimizer/node_modules/retry-request/index.js:222:19)
at PassThrough.<anonymous> (/home/ubuntu/imageoptimizer/node_modules/retry-request/index.js:163:11)
at PassThrough.emit (events.js:412:35)
at /home/ubuntu/imageoptimizer/node_modules/teeny-request/build/src/index.js:191:27
Emitted 'error' event on PassThrough instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
code: 404,
Posting my previous comment as an answer for visibility
You have to handle this exception by yourself. GCP won't throw the error directly. It only returns 404 as an output, and you have to handle it manually rather than expecting try{} catch () {} to catch this exception. Or you can request it as a new feature in issue tracker, however I am not sure how long it will take for the Google to implement this feature.

error running simple electron program

a few days ago I started to learn about electron and I started to make a small project to download youtube videos to test the things around. Here is the code
main.js:
const electron = require(‘electron’);
const path = require(‘path’);
const url = require(‘url’);
const youtubedl = require(‘youtube-dl’);
const {app, BrowserWindow, Menu, ipcMain} = electron;
let mainWindow;
app.on(‘ready’, function()
{
mainWindow = new BrowserWindow({});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, ‘index.html’),
protocol: ‘file:’,
slashes:true
}));
mainWindow.on(‘closed’, function(){
app.quit();
});
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(mainMenu);
});
exports.getUrlInformation=(arg)=>
{
var url = arg;
var options = [];
youtubedl.getInfo(url, options, function(err, urlInformation)
{
if (err) throw err;
mainWindow.webContents.send('UrlInformation', urlInformation);
});
}
index.js:
var {ipcRenderer, remote} = require(‘electron’);
var mainProcess = remote.require("./main.js");
class YouTubeDownloaderForm extends React.Component
{
constructor(props)
{
super(props);
this.state = {url: ‘’};
this.handleAddClick = this.handleAddClick.bind(this);
}
handleAddClick(event)
{
mainProcess.getUrlInformation(this.state.url);
}
I looked into devtool console and this is the error that shows up. Does this look like a installation error?
File not found (file:///c:/temp/Electron/YouTubeDownloader/node_modules/electron/dist/resources/electron.asar/browser/rpc-server.js
Stack Trace:
Uncaught Error: Could not call remote function ''. Check that the function signature is correct. Underlying error: spawn UNKNOWN
Error: Could not call remote function ''. Check that the function signature is correct. Underlying error: spawn UNKNOWN
at callFunction (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
at EventEmitter.<anonymous> (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
at emitMany (events.js:127:13)
at EventEmitter.emit (events.js:204:7)
at WebContents.<anonymous> (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
at emitTwo (events.js:106:13)
at WebContents.emit (events.js:194:7)
at callFunction (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
at EventEmitter.<anonymous> (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
at emitMany (events.js:127:13)
at EventEmitter.emit (events.js:204:7)
at WebContents.<anonymous> (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
at emitTwo (events.js:106:13)
at WebContents.emit (events.js:194:7)
at metaToValue (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:234:13)
at Object.remoteMemberFunction (C:\temp\Electron\YouTubeDownloader\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:118:18)
at YouTubeDownloaderForm.handleAddClick (<anonymous>:42:19)
at HTMLUnknownElement.callCallback (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:580:14)
at Object.invokeGuardedCallbackDev (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:619:16)
at Object.invokeGuardedCallback (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:476:27)
at Object.invokeGuardedCallbackAndCatchFirstError (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:490:43)
at executeDispatch (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:972:19)
at executeDispatchesInOrder (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:994:5)
at executeDispatchesAndRelease (https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js:1092:5)
I fixed the npmjs.com/package/youtube-dl issue by download the latest youtube-dl exe from https://youtube-dl.org/downloads/latest/youtube-dl.exe, then putting it in node_modules\youtube-dl\bin

Node-serial port as external module in webpack - module not found

I'm trying to get node-serialport to work with electron and webpack.
I'm importing serialports as external module:
# webpack.config.js
externals: {
serialport: "serialport"
}
This is the code in my app:
// read NMEA data from serial port
const SerialPort = require('serialport');
console.log(SerialPort.list());
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('/dev/tty.Redmi-ShareGPS', { baudRate: 4800 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
// Open errors will be emitted as an error event
port.on('error', function(err) {
console.log(err.message);
})
// send NMEA data to GPS.js
parser.on('data', function(data) {
// gps.update(data);
});
Trouble is in first line: const SerialPort = require('serialport');
Webpack compiles everything without error, but I have a browser console error:
Uncaught ReferenceError: serialport is not defined
at Object.<anonymous> (bundle.js:65651)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:65630)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:31520)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:25595)
at __webpack_require__ (bundle.js:20)
at _ol_ (bundle.js:63)
at bundle.js:66
Which origins at this in webpack generated bundle.js:
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
// read NMEA data from serial port
const SerialPort = __webpack_require__(316);
console.log(serialport.list());
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('/dev/tty.Redmi-ShareGPS', { baudRate: 4800 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
// Open errors will be emitted as an error event
port.on('error', function (err) {
console.log(err.message);
});
// send NMEA data to GPS.js
parser.on('data', function (data) {
// gps.update(data);
});
/***/ }),
/* 316 */
/***/ (function(module, exports) {
module.exports = serialport;
/***/ })
/******/ ]);
The error line is exactly module.exports = serialport;
According to webpack docs on externals, I suppose I somehow need to include serialport as a global variable, but the example is for jQuery which is a js file, and serialport is node module.
How to make it work?
After many hours of frustration, I moved
const SerialPort = require('serialport');
from javascript file which is supposed to be bundled by webpack to index.html:
<script>
const SerialPort = require('serialport');
</script>
<script src="dist/bundle.js"></script>
SerialPort is now recognized.
Also, it seems like webpack-dev-server doesn't work very well with Electron and serialport. I have to launch full electron app.
Try remote.
You might also want to try using remote:
const SerialPort = require( "electron" ).remote.require( "serialport" );
use eval
const serialport = eval(`require('serialport')`)

Categories