create gcs storage in node - node.js

const functions = require('firebase-functions')
const { Storage } = require('#google-cloud/storage');
let gcs = new Storage ();
const os = require('os');
const path = require('path');
exports.onFileChange = functions.storage.object().onFinalize(event => {
console.log(event);
const bucket = event.bucket;
contentType = event.contentType;
const filePath = event.name;
console.log('file detected')
if(path.basename(filePath).startsWith('renamed-')){
console.log('already renamed this file')
return;
}
const destBucket = gcs.bucket(bucket);
const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
const metadata = { contentType : contentType }
return destBucket.file(filePath).download({
destination : tmpFilePath
}).then(() => {
return destBucket.upload(tmpFilePath, {
destination:'renamed-'+ path.basename(filePath),
metadata: metadata
})
})
});
the error is:-
`Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /srv/node_modules/p-limit/index.js:30
} catch {}
^
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/node_modules/#google-cloud/storage/build/src/bucke here t.js:25:16)
`

The error message implies you have a syntax error in your function.
Change the line contentType = event.contentType; to const contentType = event.contentType; and your syntax er

Related

What is the Unexpected Token syntax error in line six?

I'm trying to learn how to create NFTs on the Ethereum block chain.
In terminal (Ubuntu 20.04.3 LTS)
Aki-Zeta:~/my-nft$ node scripts/mint-nft.js
I keep getting
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
Syntax Error Unexpected Token {
see bottom for full error
Here is my code using VScode
require("dotenv").config()
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
const web3 = createAlchemyWeb3(API_URL)
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json")
const contractAddress = "0xf469355dc12e00d8cda65b3a465bdad65da27e22"
const nftContract = new web3.eth.Contract(contract.abi, contractAddress)
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(),
}
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)
signPromise
.then((signedTx) => {
web3.eth.sendSignedTransaction(
signedTx.rawTransaction,
function (err, hash) {
if (!err) {
console.log(
"The hash of your transaction is: ",
hash,
"\nCheck Alchemy's Mempool to view the status of your transaction!"
)
} else {
console.log(
"Something went wrong when submitting your transaction:",
err
)
}
}
)
})
.catch((err) => {
console.log(" Promise failed:", err)
})
}​
mintNFT(
"https://gateway.pinata.cloud/ipfs/QmcRikKfA6xdaNZkojW28xpvZYysQXSJEb52YdeRJP3GGv"
)
Is it something to do with that "{" in line 6, or something else in line 6?
Prior to running this script I ran "npm install #alch/alchemy-web3", and verified the directories exist (both by going there and with cd). Other people with similar issues are missing something, and I have no idea what I'm missing. I have checked for spurious spaces and semicolons but I am not experienced with this language.
I have been using the tutorials off of the Ethereum project site.
full error
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:471:10)
at startup (node.js:117:18)
at node.js:951:3
I had exactly the same error, and it was just a spurious character in my VScode editor, same example as you from ethereum.org.
As you can see in line 24
change const { createAlchemyWeb3 } to const { createAlchemyWeb3 } = require("#alch/alchemy-web3")

How do I extract a tar file in nodejs using the pipeline() method?

My current code looks like this:
const gzip2 = zlib.createUnzip();
const pack2 = new tar.Unpack();
const source2 = Readable.from('public/img.tar.gz');
const destination2 = fs.createWriteStream('public/images2');
pipeline(source2, gzip2, pack2, destination2, (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
});
But I'm getting this error:
internal/streams/pipeline.js:108
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "val" argument must be an instance of Readable, Iterable, or AsyncIterable. Received an instance of Unpack
at makeAsyncIterable (internal/streams/pipeline.js:108:9)
at pipeline (internal/streams/pipeline.js:265:15)
at Object.<anonymous> (/mnt/c/index.js:39:1)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
I've also tried
const pack2 = tar.extract();
without luck.
If anyone can help me to extract this tar file using pipeline, so that I can also unzip the file. I would be very grateful. I've seen people use .pipe(tar.extract()) online, but I'm trying to keep my code as clean and uniform as possible. This: https://www.npmjs.com/package/tar has unfortunately not been very helpful.
const tar = require('tar.gz2')
var read = tar().createReadStream('/public/images');
var write = fs.createWriteStream('compressed.tar.gz');
pipeline(read,write,
(err) => {
if (err) {
throw err
}
})

My discord js command handler not working

Hey i can't seem to get my command handler to work with multiple command file could someone help me with this i tried multiple ways i can't seem to get it to work with multiple folders. I'm a bit new to Discord js as well i had one working then i wanted to make it more organized and i can't seem to get it to work
const fs = require(`fs`);
module.exports = (client, Discord) => {
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
const command_files = fs.readdirSync('./moderationcommands/').filter(file => file.endsWith('.js'));
for (const file of command_files) {
const command = require(`../commands/${file}`, `../moderationcommands/${file}`);
if (command.name) {
client.commands.set(command.name, command);
} else {
continue;
}
}
}
Here's the error
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
C:\Users\lolzy\OneDrive\Desktop\discordbot\handlers\command_handler.js:5
const command_files = fs.readdirSync('./moderationcommands/').filter(file => file.endsWith('.js'));
^
SyntaxError: Identifier 'command_files' has already been declared
at wrapSafe (internal/modules/cjs/loader.js:984:16)
at Module._compile (internal/modules/cjs/loader.js:1032:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at C:\Users\lolzy\OneDrive\Desktop\discordbot\main.js:13:5
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\lolzy\OneDrive\Desktop\discordbot\main.js:12:38)
PS C:\Users\lolzy\OneDrive\Desktop\discordbot>
You named two variables exactly the same:
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
const command_files = fs.readdirSync('./moderationcommands/').filter(file => file.endsWith('.js'));
You just have to make sure, that they have different names

SyntaxError: Unexpected token { in JSON at position 0

I am trying to parse a JSON file but getting an expected token, { at position 0.
SolaceConnetionParser.js
class SolaceConnectionParser {
constructor() { }
//TODO: cannot parse json correctly
parse(filepath) {
const connectionArgs = [];
console.log('File path: ' + filepath);
const rawData = fs.readFileSync(filepath, 'utf-8').toString;
const contents = JSON.parse(rawData);
return contents;
}
}
module.exports = SolaceConnectionParser;
const path = require('path');
const fs = require('fs');
const parser = new SolaceConnectionParser();
const filepath = path.join(__dirname + '../../../configs/test.json');
console.log(parser.parse(filepath));
test.json:
{
"key": "value"
}
Expected:
Rest of statements in code should output to console (i.e.: JSON contents).
Actual:
$ node SolaceConnectionParser.js
File path: C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\configs\test.json
undefined:1
{
^
SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at SolaceConnectionParser.parse (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:9:31)
at Object.<anonymous> (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:26:31)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
JSON objects are represented as Strings and fs.readFileSync() returns a Buffer.
Change
const rawData = fs.readFileSync(filepath, 'utf-8');
to
const rawData = fs.readFileSync(filepath, 'utf-8').toString();
and you should be good to go.
after applying Rob Raisch's answer and also trimming the string, problem was solved.
const rawData = fs.readFileSync(filepath, 'utf-8').toString().trim();

Load and modify svg files from node.js

We have an API that should send png files. This png files are composition of several svg files and some changes in attributes: background-color, image size..
We are using node.js on the server.
I've tried without success using d3 in order to modify SVG files & Jsdom to use d3 on the backend:
var fs = require('fs');
var d3 = require('d3');
var JSDOM = require('jsdom').JSDOM;
var outputLocation = 'test.svg';
const window = (new JSDOM(`<html><head></head><body></body></html>`, { pretendToBeVisual: true })).window;
window.d3 = d3.select(window.document); //get d3 into the dom
d3.xml("./react02.svg").mimeType("image/svg+xml").get(function(error, xml) {
var importedNode = document.importNode(xml.documentElement, true);
if (error) throw error;
console.log(xml);
window.d3.select('body')
.append('div').attr('class', 'container')
.appendChild(importedNode);
});
fs.writeFileSync(outputLocation, window.d3.select('.container').html()) //using sync to keep the code simple
But I always get an error:
TypeError: Cannot read property 'innerHTML' of null
at Selection.selection_html [as html] (/home/juanda/kk2/node_modules/d3-selection/build/d3-selection.js:793:20)
at Object.<anonymous> (/home/juanda/kk2/test2.js:18:65)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:201:16)
at bootstrap_node.js:626:3
Can't find any example / library reading and modifing svg files on server side.
Moved from d3 to snapsvg as I don't need data analysis, just play with the svg itself.
This is my code:
let {JSDOM} = require('jsdom')
var resolve = require('resolve');
resolve('snapsvg', { basedir: __dirname }, function (err, resource) {
if (err) console.error(err)
else {
const options = {
runScripts: "dangerously",
resources: "usable",
url: "file:///prueba.html" // avoid cors error reading svg file
};
const dom = new JSDOM(`
<!DOCTYPE html><html><body><div id="test"></div></body></html>
`, options);
var script = dom.window.document.createElement('script');
script.src = `file://${resource}`;
var head= dom.window.document.getElementsByTagName('head')[0];
head.appendChild(script);
// console.log(dom.serialize())
script.onload = function () {
// console.log("Script loaded and ready");
// console.log(dom.window)
var s = dom.window.Snap("#test");
dom.window.Snap.load("file:///Users/juandaniel/Code/prueba/2375.svg", onSVGLoaded);
function onSVGLoaded(data) {
s.append(data);
console.log(s.node.innerHTML)
}
};
}
});

Resources