NodeJS Write and Read simple file from lambda - javascript

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

Related

Discord bot js ./src/functions/handleCommands.js

I am trying to create a moderation bot and I face a error that shows I don't have commands (Thats my first project).
Here is the complete error:
at Object.readdirSync (node:fs:1450:3)
at Object.<anonymous> (C:\Users\artsi\OneDrive\Desktop\goldman bot\src\bot.js:13:6)
at Module._compile (node:internal/modules/cjs/loader:1119:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1173:10)
at Module.load (node:internal/modules/cjs/loader:997:32)
at Module._load (node:internal/modules/cjs/loader:838:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:18:47 {
errno: -4052,
syscall: 'scandir',
code: 'ENOTDIR',
path: './src/functions/handleCommands.js'
}
Here is my bot.js
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];
const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync(`.src/functions/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of functionFiles)
require(`./functions${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);

Error occurred while pinning file to IPFS: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string

When i add the files to another project I get the following error and i can't figure out why.
When I run "node scripts1/runScript.js" error i get is:
Error occurred while pinning file to IPFS: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received undefined
at new NodeError (node:internal/errors:371:5)
at validateString (node:internal/validators:119:11)
at Url.parse (node:url:169:3)
at Object.urlParse [as parse] (node:url:156:13)
at dispatchHttpRequest (C:\Users\alaiy\Documents\NFTs\nft-mix-main\node_modules\axios\lib\adapters\http.js:118:22)
at new Promise (<anonymous>)
at httpAdapter (C:\Users\alaiy\Documents\NFTs\nft-mix-main\node_modules\axios\lib\adapters\http.js:48:10)
at dispatchRequest (C:\Users\alaiy\Documents\NFTs\nft-mix-main\node_modules\axios\lib\core\dispatchRequest.js:58:10)
at Axios.request (C:\Users\alaiy\Documents\NFTs\nft-mix-main\node_modules\axios\lib\core\Axios.js:108:15)
at wrap (C:\Users\alaiy\Documents\NFTs\nft-mix-main\node_modules\axios\lib\helpers\bind.js:9:15) {
code: 'ERR_INVALID_ARG_TYPE'
}
The runScript.js code is :
const path = require('path');
const pinFileToIPFS = require('./pinFileToIPFS');
const filePath = path.join(__dirname, '../img/Toad-Licking-Mario.jpg');
// const filePath = path.join(__dirname, '../data/metadata.json');
pinFileToIPFS(filePath);
The pinFileToIPFS.js file which contains the "url: pinataEndpoint" i think the error message is referring too:
require('dotenv').config();
const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');
const { storeDataToFile } = require('./ipfsHelper.js');
// Calls Pinata API's to pin file to IPFS
const pinFileToIPFS = async (filePath) => {
const pinataEndpoint = process.env.PINATA_ENDPOINT;
const pinataApiKey = process.env.PINATA_API_KEY;
const pinataApiSecret = process.env.PINATA_API_SECRET;
const form_data = new FormData();
try {
form_data.append('file', fs.createReadStream(filePath));
const request = {
method: 'post',
url: pinataEndpoint,
maxContentLength: 'Infinity',
headers: {
pinata_api_key: pinataApiKey,
pinata_secret_api_key: pinataApiSecret,
'Content-Type': `multipart/form-data; boundary=${form_data._boundary}`,
},
data: form_data,
};
console.log('request:', request);
const response = await axios(request);
console.log('Successfully pinned file to IPFS : ', response);
await storeDataToFile(response.data);
console.log('Successfully added IPFS response to json file');
} catch (err) {
console.log('Error occurred while pinning file to IPFS: ', err);
}
};
module.exports = pinFileToIPFS;
Lastly my .env file is:
# export PRIVATE_KEY=asafdagadd
# export WEB3_INFURA_PROJECT_ID=asdfsdf
# export ETHERSCAN_TOKEN=asdfasdfasdf
export IPFS_URL=blah blah
export UPLOAD_IPFS=true
export PINATA_API_KEY='blah blah'
export PINATA_API_SECRET='blah blah'
export PINATA_ENDPOINT="https://api.pinata.cloud/pinning/pinFileToIPFS"
I can upload the package.json file aswell if needed.
Any help is appreciated!
SOLUTION: Turned out the export syntax I was using in my .env file should not be there. export syntax is for python scripts which I was previously using.
As I am running javascript scripts, I deleted the export syntax and everything worked like a charm!
I was facing same error, the i find out that my config folder suppose to be in the folder in which I was executing it from.
This error comes when your url value is not getting the env variables.
So in my case solution was something like this-
config/
--default.json
scripts/
--server.js
So it was searching config folder inside scripts folder.
Later I run my file outside from scripts folder then it worked fine.
node scripts/server.js

It apparently fails to find the module

The code is this and when I try to turn my bot on I get a error that it can't find the file to execute the command.
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFolders = fs.readdirSync('./commands')
for(const folder [enter image description here][1]of commandFolders){
const command_files = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'))
for(const file of command_files){
const command = require(`./commands/${folder}/${file}`);
if(command.name){
client.commands.set(command.name, command);
}else {
continue
}
}
}
}
This is the error I get when I turn my bot on.
node:internal/modules/cjs/loader:944
throw err;
^
Error: Cannot find module './commands/Fun/8ball.js'
Require stack:
- C:\Users\Desktop\Discordproject\handlers\command_handler.js
- C:\Users\Desktop\Discordproject\index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)
at Function.Module._load (node:internal/modules/cjs/loader:774:27)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at module.exports (C:\Users\Desktop\Discordproject\handlers\command_handler.js:8:25)
at C:\Users\famil\Desktop\Discordproject\index.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\Desktop\Discordproject\index.js:10:38)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\Desktop\\Discordproject\\handlers\\command_handler.js',
'C:\\Users\\Desktop\\Discordproject\\index.js'
]
}
Directory Structure:
Your command_handler.js file is inside /handlers/. ./ is used to access the current directory.
Doing ./commands/ doesn't work because the commands folder is not inside of /handlers/
You must first exit the current folder (using ../), then access.
Change all of the './commands' to '../commands'

Metadata of ffmpeg is undefined in electron app

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

Copy a source file to another destination in Nodejs

I'm trying to copy an image from a folder to another using fs-extra module .
var fse = require('fs-extra');
function copyimage() {
fse.copy('mainisp.jpg', './test', function (err) {
if (err)
return console.error(err)
});
}
This is my directory
and this is the error I get all the time:
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\mainisp.jpg", message: "ENOENT: no such file or directory, lstat
'E:\mainisp.jpg'"}
and by changing destination to ./test/ I get this error
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\Development\Node apps\Node softwares\Digital_library\mainisp.jpg",
message: "ENOENT: no such file or directory, lstat 'E:\Devel…
apps\Node softwares\Digital_library\mainisp.jpg'"}
Note: I'm not testing this in browser. It's an Nwjs app and the pics of error attached are from Nwjs console.
You can do this using the native fs module easily using streams.
const fs = require('fs');
const path = require('path');
let filename = 'mainisp.jpg';
let src = path.join(__dirname, filename);
let destDir = path.join(__dirname, 'test');
fs.access(destDir, (err) => {
if(err)
fs.mkdirSync(destDir);
copyFile(src, path.join(destDir, filename));
});
function copyFile(src, dest) {
let readStream = fs.createReadStream(src);
readStream.once('error', (err) => {
console.log(err);
});
readStream.once('end', () => {
console.log('done copying');
});
readStream.pipe(fs.createWriteStream(dest));
}
Try:
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./mainisp.jpg'), './test/mainisp.jpg');
As you can see in the error message, you're trying to read the file from E:\mainisp.jpg instead of the current directory.
You also need to specify the target path with the file, not only the destination folder.
Try:
const fs = require('fs');
fs.copyFileSync(src, dest);

Categories