How to solve error "SyntaxError: Unexpected token '?'" - node.js

I'm not sure what's wrong. I deleted my code and downloaded it then uploaded it again and now I get this error.
Code: https://replit.com/#hi12167pies/webcord#index.js (Click code for code and output for output)
Error:
/home/runner/C8AU9ceLyjc/node_modules/discord.js/src/rest/RESTManager.js:32
const token = this.client.token ?? this.client.accessToken;
^
SyntaxError: Unexpected token '?'
I have no idea whats wrong since it's in the node_modules folder.
If you have problems viewing it here is the code:
const http = require("http")
const discord = require("discord.js")
const client = new discord.Client()
const config = require("./config.json")
const fs = require("fs")
// const readLine = require("readline")
// const rl = readLine.createInterface({
// input: process.stdin,
// output: process.stdout
// })
let msgs = {
"873195510251532348": [],
"873195522633105429": []
}
client.on("ready", () => {
console.log("ready discord")
})
client.on("message", (message) => {
if (message.author.bot) return
if (!config.chats.includes(message.channel.id.toString())) return
msgs[message.channel.id].push({
"username": message.author.tag,
"content": message.content,
"type": "0"
})
})
http.createServer((req,res) => {
const url = req.url.split("?")[0]
let query = {}
req.url.slice(req.url.split("").indexOf("?")).slice(1).split("&").forEach((e) => {
const splited = e.split("=")
query[splited[0]] = splited[1]
})
if (query.q == "messages") {
let msg = []
let i = 0
while (msgs[query.code].length > i) {
const e = msgs[query.code][msgs[query.code].length - (i+1)]
msg.push(e)
i++
}
res.write(JSON.stringify(msg))
res.end()
} else if (query.q == "post") {
let name = query.name.split("%20").join(" ")
let content = query.content.split("%20").join(" ")
client.channels.cache.get(query.code).send(`**${name}**: ${content}`)
msgs[query.code].push({
"username": name,
"content": content,
"type": "1"
})
res.end()
} else if (url == "/robot" && query.istrue == "true") {
res.write("Robot!")
res.end()
} else {
let path
if (!query.code) {
path = "./code.html"
} else {
if (!config.chats.includes(query.code)) {
path = "./invaildcode.html"
} else {
path = "./chat.html"
}
}
fs.readFile(path, (er, da) => {
if (er) res.write("Could not get index.html")
res.write(da)
res.end()
})
}
}).listen(80, (err) => {
if (err) throw err
console.log("listening webserver")
})
client.login(process.env.TOKEN)
I am aware my code is not good right now, I am rewriting it but I still want to know what the error is.

repl.it uses node v12.22.1 but the nullish coalescing operator (??), is relatively new and was added in node v14.
So to use the ?? operator you need to update node in repl.it.
Which you can do by following this repl.it forum post by lukenzy.
Create a file and name it .replit
Inside it, copy and paste the following code:
run = """
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
export NVM_DIR=\"$HOME/.nvm\"
[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\"
[ -s \"$NVM_DIR/bash_completion\" ] && \\.\"$NVM_DIR/bash_completion\"
nvm install 14
node index.js
"""
This will install and use the latest Node.js v14 (14.17.4).
If u want to use a different version, change nvm install 14 to any other
number.
Also, change node index.js to the file u want to run.

You are getting this error because you are using an older version of node that didn't support nullable for some packages.
Simply change node version of yours.
You can simply change node versions using 'nvm'. follow this git repo https://github.com/nvm-sh/nvm

Related

How to display prompts and command outputs simultaneously in Nodejs?

I am trying to make a shell environment using Nodejs and encountered the following flaw in my program. I tried using the readline-sync and prompt-sync for resolving the issue and described about the problem next.
I am having the below code:
const prompt = require('prompt-sync')({sigint: true});
const { spawn } = require("child_process");
const os = require('os')
working_dir = os.homedir();
user_cmd = "";
while (user_cmd != "exit") {
user_cmd = prompt(working_dir + " >");
if (user_cmd.match("ls") != null) {
const ls = spawn("ls");
ls.stdout.on("data", data => {
console.log(`${data}`);
});
ls.stderr.on("data", data => {
console.log(`${data}`);
});
ls.on('error', (error) => {
console.log(`${error.message}`);
});
}
}
I want output in this way:
OUTPUT AFTER EACH PROMPT
hi#SanthoshSingh:/mnt/e/Atri Labs$ node shell.js
/home/hi >ls
hi.js
ls.js
node_modules
package-lock.json
package.json
shell.js
/home/hi >exit
but getting the output in this way:
AFTER ALL PROMPTS GETTING THE OUTPUT
hi#SanthoshSingh:/mnt/e/Atri Labs$ node shell.js
/home/hi >ls
/home/hi >exit
hi.js
ls.js
node_modules
package-lock.json
package.json
shell.js
Get me a solution people :-)
prompt-sync blocks the /dev/tty. Unless you exit from it you will not be able to print stdout buffer to tty(screen). You exit from it(prompt-sync) only after you exit the while loop.
following is an alternate implementation that fixes the above issue:
const prompt = require('prompt-sync')({sigint: true});
const { spawn } = require("child_process");
const os = require('os')
working_dir = os.homedir();
user_cmd = "";
function call() {
user_cmd = prompt(working_dir + " >");
const ls = spawn(user_cmd);
ls.stdout.on("data", data => {
console.log(`${data}`);
ls.kill('SIGINT')
});
ls.stderr.on("data", data => {
console.log(`${data}`);
});
ls.on('error', (error) => {
console.log(`${error.message}`);
ls.kill('SIGINT')
});
ls.on('exit', (error) => {
call()
});
}
const interval = setInterval(function () { }, 1000)
process.on('exit', () => {
clearTimeout(interval)
})
call()

JSON stringify sporadically replaces separator with closing square bracket

I am running a node.js script that culls through a directory and extracts any regex matches it finds, then pushes them onto an array. Once the query has run, I am stringifying the array into a standalone JSON file for safekeeping until it's needed.
I'm running into sporadic errors where the array in the JSON file is malformed and causes an error when I try to parse it out later on. It is sporadic, and I cannot determine a pattern, but every time (so far) the character that is causing the error is a closing square bracket - just like the one between the 2nd and 3rd elements below:
["first string","second string"]"third string"]
It's almost as if my array.push() is just adding another element onto the end of the existing array, and "forgetting" to change the closing square bracket to a comma...
I have searched, but cannot find references to a known error that would cause this. Has anyone seen this before?
Environment:
Node.js v19.0.0 | Ubuntu 22.04.1 LTS | Intel i7 processor
Here's my code for generating the JSON files:
const fs = require('fs');
const path = require('path');
const devPath = '/home/user/directory';
const activeReminder = [];
function buildArray() {
let getFiles = fs.readdirSync(devPath);
getFiles.forEach(file => {
splitMD(file);
});
}
function splitMD(file) {
if (path.extname(file) == ".md" & file != {}) {
let data = fs.readFileSync(file, 'utf8');
const line = data.split(/\r?\n/);
const match = line.find(element => {
extractions(element, file);
});
}
};
function extractions(element, file) {
if (element.includes("- [ ] reminder: ")) { //the - [ ] is markdown for Obsidian
const datedReminder = "- [ ] [["+file+"]]" + element.split('- [ ] reminder:')[1]
activeReminder.push(datedReminder);
buildReminderJSON();
}
}
function buildCcioJSON() {
const reminderJSON = JSON.stringify(activeReminder);
fs.writeFile("reminder.json", reminderJSON, 'utf8', function (err) {
if (err) {
console.log("Error while writing CCIO JSON:");
return console.log(err);
}
})
}
buildArray();
module.exports = { buildArray };
I don't know what's causing the anomaly described above, but I created a script to correct it as a workaround until I can figure out a root cause. I'm running it as a crontab a few minutes after the crontab that creates the original array.
const fs = require('fs')
const path = require('path')
const devPath = '/home/user/directory'
function cleanup() {
let getFiles = fs.readdirSync(devPath);
getFiles.forEach(file => {
splitJSON(file);
});
}
function splitJSON(file) {
if (path.extname(file) == ".json" & file != {}) {
let data = fs.readFileSync(file, 'utf8');
const line = data.split(/\r?\n/);
const match = line.find(element => {
jsonCheck(element, file);
});
}
};
function jsonCheck(element, file) {
if (element.includes("\"]\"")) {
fs.readFile(file, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/\"\]\"/g, '","');
fs.writeFile(file, result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
}
}
cleanup();
module.exports = { cleanup };

GoogleError: Error opening file: gs://mybucket/a.subpath/output.json

I am trying to do OCR on a PDF and am having difficulty getting it to work. I am getting this error:
GoogleError: Error opening file: gs://mybucket/a.subpath/output.json
at Operation._unpackResponse (/Users/my/project/node_modules/google-gax/build/src/longRunningCalls/longrunning.js:148:31)
at /Users/my/project/node_modules/google-gax/build/src/longRunningCalls/longrunning.js:134:18 {
code: 7
}
When running this Node.js script:
const fs = require('fs')
const vision = require('#google-cloud/vision').v1
const client = new vision.ImageAnnotatorClient()
parse('a.something')
function parse(name) {
var bucketName = `mybucket`
const features = [{type: 'DOCUMENT_TEXT_DETECTION'}]
let requests = []
let i = 0
while (i < 10) {
requests.push({
inputConfig: {
mimeType: 'application/pdf',
gcsSource: {
uri: `gs://${bucketName}/${name}.${i + 1}.pdf`
},
},
features: features,
outputConfig: {
gcsDestination: {
uri: `gs://${bucketName}/${name}.${i + 1}/`,
},
},
})
i++
}
const request = {
requests
}
client.asyncBatchAnnotateFiles(request).then(x => {
let [operation] = x
operation.promise().then(y => {
let [filesResponse] = y
const destinationUri =
filesResponse.responses[0].outputConfig.gcsDestination.uri
console.log('Json saved to: ' + destinationUri)
process.exit()
}).catch(e => {
console.log(e)
process.exit()
})
})
}
This is straight from the docs pretty much.
At first I just went into the console and uploaded the PDFs into Cloud Storage manually. I was logged in as foo#gmail.com. A few days before I created a JSON API key to export in the shell, for project bar (which I created when logged in as foo#gmail.com). I then got this error above. So what I tried doing is adding a new member to the project, who had my email foo#gmail.com. Then I gave them the roles I think equivalent to roles/storage.legacyObjectOwner, which were these:
Then, when I run the Node.js script, I get this error still. I don't know what's going on or how to fix it, any ideas?

Getting unexpected token when running my code that is supposed to post gifs from giphy

Im getting a unexpected token, but I'm not sure what I'm doing wrong.
I tried to delete all modules and then renstall them but that didnt help
import { Client } from 'discord.js';
const client = new Client();
var GphApiClient = require('giphy-js-sdk-core')
client = GphApiClient("MyAPIkey");
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.content.startsWith(`${prefix}!send`)) {
giphy.search('gifs', {"q": "cats"})
.then((response) => {
var totalResponses = response.data.length;
var responseIndex = Math.floor((Math.random() * 10) + 1) %
totalResponses;
var responseFinal = response.data[responseIndex];
message.channel.send("Kapo on teel", {
files: [responseFinal.images.fixed_height.url]
})
})
};
})
This is the error I was getting:
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:811:22)
I think your syntax error is because you were trying to use ES6 modules (eg: import/export) without using something to transpile (eg: babel). There's more on that here if you're interested. In other words, I don't think you can use import. You have to use require. I also fixed the issues with client being defined multiple times. However, this code below still won't work because prefix was never defined anywhere.
const { Client } = require('discord.js');
var GphApiClient = require('giphy-js-sdk-core')
const discordClient = new Client();
giphyClient = GphApiClient('MyAPIkey');
discordClient.once('ready', () => {
console.log('Ready!');
});
discordClient.on('message', message => {
if (message.content.startsWith(`${prefix}!send`)) {
giphyClient.search('gifs', { "q": "cats" })
.then((response) => {
const totalResponses = response.data.length;
const responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
const responseFinal = response.data[responseIndex];
message.channel.send("Kapo on teel", {
files: [responseFinal.images.fixed_height.url]
});
})
} else {
console.log(`message doesn't start with ${prefix}!send`)
}
});

npm react-native-fetch-blob - "RNFetchBlob.fetch is not a function"

I am using the npm package react-native-fetch-blob.
I have followed all the steps from the git repository to use the package.
I then imported the package using the following line:
var RNFetchBlob = require('react-native-fetch-blob');
I am trying to request a BLOB containing an image from the a server.
This is my main method.
fetchAttachment: function(attachment_uri) {
var authToken = 'youWillNeverGetThis!'
var deviceId = '123';
var xAuthToken = deviceId+'#'+authToken
//Authorization : 'Bearer access-token...',
// send http request in a new thread (using native code)
RNFetchBlob.fetch('GET', config.apiRoot+'/app/'+attachment_uri, {
'Origin': 'http://10.0.1.23:8081',
'X-AuthToken': xAuthToken
})
// when response status code is 200
.then((res) => {
// the conversion is done in native code
let base64Str = res.base64()
// the following conversions are done in js, it's SYNC
let text = res.text()
let json = res.json()
})
// Status code is not 200
.catch((errorMessage, statusCode) => {
// error handling
});
}
I keep receiving the following error:
"Possible Unhandled Promise Refection(id: 0): TypeError: RNFetchBlob.fetch is not a function".
Any ideas?
The issue is you are using ES5 style require statements with a library written against ES6/ES2015. You have two options:
ES5:
var RNFetchBlob = require('react-native-fetch-blob').default
ES6:
import RNFetchBlob from 'react-native-fetch-blob'
My import looks like this : import RNFetchBlob from 'rn-fetch-blob';
but I'v got an error : TypeError: RNFetchBlob.scanFile is not a function
My code:
const downloadAudio = async () => {
const { config, fs } = RNFetchBlob;
const meditationFilesPath =
Platform.OS == 'android'
? `${fs.dirs.DownloadDir}/meditations/${id}`
: `${fs.dirs.DocumentDir}/meditations/${id}`;
let audio_URL = track;
let options = {
fileCache: true,
path: meditationFilesPath + `/${id}.mp3`,
addAndroidDownloads: {
// Related to the Android only
useDownloadManager: true,
notification: true,
path: meditationFilesPath + `/${id}.mp3`,
description: 'Audio',
},
};
try {
const resAudio = await config(options).fetch('GET', audio_URL.uri);
if (resAudio) {
const audio = await RNFetchBlob.fs.scanFile([
{ path: resAudio.path(), mime: 'audio/mpeg' },
]);
console.log('res -> ', audio);
Alert.alert('Audio Downloaded Successfully.');
}
} catch (error) {
console.error('error from downloadAudio', error);
}
};

Resources