Npm run start looking for wrong path - javascript

im trying to use google text to speech api . And node js looking for wrong directory.
Error: The file at /home/user/Downloads/service-account-file.json does not exist, or it is not a file. ENOENT: no such file or directory, lstat '/System/Volumes/Data/home/user'
it says your .json not exist in this directory which is correct. But there is nothing that i can provide path for this. Also when i try to move my json to path that error specified. It is still saying same thing.
//and this is my code
const textToSpeech = require('#google-cloud/text-to-speech');
// Import other required libraries
const fs = require('fs');
const util = require('util');
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
async function quickStart() {
// The text to synthesize
const text = 'hello, world!';
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML voice gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
// Performs the text-to-speech request
const [response] = await client.synthesizeSpeech(request);
// Write the binary audio content to a local file
const writeFile = util.promisify(fs.writeFile);
await writeFile('/Applications/development/gmvoice/output.mp3', response.audioContent, 'binary',function (err) {
if (err) throw err; console.log('Results Received');
});
console.log('Audio content written to file: output.mp3');
}
quickStart();

Related

ENOENT: no such file or directory, open './data/databases.json'

am trying to write json data from a file contained in model folder to another file inside data folder and the two folders are contained in server folder. but i keep on getting the error message that there is no such file directory. the code below is inside model/model.ts file and the file i want to write to is in data/databases.json and both are inside server folder. i have tried using the following path ./data/databases.json, ../data/databases.json but still not working. the folder is server/models/model.ts
let Products = require("../data/product.json") // i was able to import from the same file can't write to it using the same path
const fs = require("fs")
const creat = (newInfo:any) => {
return new Promise((resolve,reject)=>{
let id = companyInfo.length+1
let value = {...newInfo,"id":id}
companyInfo.push(value)
fs.writeFileSync('../data/databases.json',JSON.stringify(companyInfo, null, 2))
resolve(value)
})
}
export {creat}
i have another file where i call the above function and the folder path is server/controller/controller.ts and below is the code
import {creat} from "../models/model" // importing the function here
import http, { IncomingMessage, Server, ServerResponse } from "http";
const creatCompanyinfo = async (req:IncomingMessage,res:ServerResponse)=>{
let body =""
req.on("data",(chunk)=>{
body += chunk.toString()
})
req.on("end",async ()=>{
let newInfo = JSON.parse(body)
let result = await creat(newInfo)
res.setHeader("Content-Type","application/json")
res.end(JSON.stringify(result))
})
}
export {creatCompanyinfo}
and finally the last file that handles the routing and the path is server/app.ts.
below is the code
import http, { IncomingMessage, Server, ServerResponse } from "http";
import {creatCompanyinfo} from "./controller/controller" //importing the function here
const server: Server = http.createServer((req: IncomingMessage, res: ServerResponse) => {
if(req.url === "/companies" && req.method==="POST"){
creatCompanyinfo(req,res)
}
}
this is the path to the json file am writting to server/data/databases.json
below is the file structure
`server/`
`controller/controller.ts`
`data/databases.json`
`model/model.ts`
`app.ts`
below is the error message am getting
Server Running at Port 4000.....
node:fs:585
handleErrorFromBinding(ctx);
^
Error: ENOENT: no such file or directory, open './data/databases.json'
at Object.openSync (node:fs:585:3)
at Object.writeFileSync (node:fs:2170:35)
at /Users/dec/Challenges/week-5-task-stanzealot/server/lib/models/model.js:28:12
at new Promise (<anonymous>)
at Object.creat (/Users/dec/Challenges/week-5-task-stanzealot/server/lib/models/model.js:24:12)
at IncomingMessage.<anonymous> (/Users/dec/Challenges/week-5-task-stanzealot/server/lib/controller/controller.js:44:36)
at IncomingMessage.emit (node:events:539:35)
Behavior of relative path in import() is different from relative path in fs methods.
import path is relative to source file, but fs path is relative to working directory.
Try converting your path to an absolute path:
const path = require("path");
const aPath = path.resolve(__dirname, '../data/databases.json')
fs.writeFileSync(aPath ,JSON.stringify(companyInfo, null, 2))

Node.js: [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined

I'm trying to make a discord bot that saves images sent to it into a folder, and I'm getting this error:
TypeError: [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined.
This is my code:
const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();
var prefix = "."
client.on("ready", () => {
client.user.setStatus('online');
console.log("Bot is on.")
});
client.on("message", message => {
console.log(__dirname)
var image = message.attachments.first()
fs.writeFileSync(`./${image.name}`, image.file);
})
client.login(process.env.token);
Note: I'm using Discord.js v12.5.3
There is no file property on attachments. There is a url property though from where you can download the image. You can use node-fetch to fetch the file (you'll need to install it by running npm i node-fetch#2 in your command line). Once the file is fetched, you can use fs.writeFileSync().
The following code works fine:
// using discord.js v12
const { Client } = require('discord.js');
const fetch = require('node-fetch');
const fs = require('fs');
const client = new Client();
const prefix = '.';
client.on('message', async (message) => {
if (message.author.bot) return;
const image = message.attachments.first();
if (!image)
return console.log('No attached image found');
// add more if needed
const imageFiles = ['image/gif', 'image/jpeg', 'image/png', 'image/webp'];
if (!imageFiles.includes(image.contentType))
return console.log('Not an image file');
try {
const res = await fetch(image.url);
const buffer = await res.buffer();
fs.writeFileSync(`./${image.name}`, buffer);
} catch (error) {
console.log(`Error reading/writing image file:`, error);
}
});

Trying to separate my SendGrid html email templates on my node server

I'm running a node server and I'm sending emails with SendGrid. I need to separate my email HTMLs from my js files so I can modify them from a single base. What I have now is this:
const express = require('express')
const config = require('config')
const sgMail = require('#sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
sgMail.setApiKey(sendKey)
const msg = {
to: "test#test.com",
from: "test#test.com",
subject: 'Welcome To The App',
text: 'Text is here',
html: <strong>HTML HERE</strong>
}
sgMail.send(msg)
I want to call my HTML property outside of my current js file instead of writing HTML inside my msg object.
How can I have a separate welcomeEmail.html file and add it to my msg object in my js file?
I've tried fs module but all I have is
Error: ENOENT: no such file or directory, open './welcomeEmail.html'
I couldn't be able to read my HTML file anyway.
Any idea of what I'm missing?
You can use fs, you probably have read from wrong path.
Use this:
fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{//do Something});
Make sure welcomeEmail.html is in the right place in your project.
Please remember readFile is async so you should do the rest of your code in the callback, so your code should be something like this (depends on what is the use case):
const express = require('express')
const config = require('config')
const sgMail = require('#sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
const fs = require('fs')
sgMail.setApiKey(sendKey)
fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{
if(err){
console.log(err);
}
else{
let msg = {
to: "test#test.com",
from: "test#test.com",
subject: 'Welcome To The App',
text: 'Text is here',
html: content
}
sgMail.send(msg)
}
});

Upload Image from Google Cloud Function to Cloud Storage

I'm attempting to handle file uploads using a Google Cloud Function. This function uses Busboy to parse the multipart form data and then upload to Google Cloud Storage.
I keep receiving the same error: ERROR: { Error: ENOENT: no such file or directory, open '/tmp/xxx.png' error when triggering the function.
The error seems to occur within the finish callback function when storage.bucket.upload(file) attempts to open the file path /tmp/xxx.png.
Note that I can't generate a signed upload URL as suggested in this question since the application invoking this is an external, non-user application. I also can't upload directly to GCS since I'll be needing to make custom filenames based on some request metadata. Should I just be using Google App Engine instead?
Function code:
const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
const Storage = require('#google-cloud/storage');
const _ = require('lodash');
const projectId = 'xxx';
const bucketName = 'xxx';
const storage = new Storage({
projectId: projectId,
});
exports.uploadFile = (req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
const uploads = []
const tmpdir = os.tmpdir();
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const filepath = path.join(tmpdir, filename)
var obj = {
path: filepath,
name: filename
}
uploads.push(obj);
var writeStream = fs.createWriteStream(obj.path);
file.pipe(writeStream);
});
busboy.on('finish', () => {
_.forEach(uploads, function(file) {
storage
.bucket(bucketName)
.upload(file.path, {name: file.name})
.then(() => {
console.log(`${file.name} uploaded to ${bucketName}.`);
})
.catch(err => {
console.error('ERROR:', err);
});
fs.unlinkSync(file.path);
})
res.end()
});
busboy.end(req.rawBody);
} else {
res.status(405).end();
}
}
I eventually gave up on using Busboy. The latest versions of Google Cloud Functions support both Python and Node 8. In node 8, I just put everything into async/await functions and it works fine.

How to pass .json file name as argument to command line in node.js

I run app.js with command node app.js
It executes const inputData = require('./input.json');
Is it possible pass file name as argument to const inputData = require('./file.json'); from command line? I mean:
node app.js file.json
I am totally new to this trickery, have no theoretical point. From where I should start? Many thanks for all possible help.
Much obliged,
You can use the process.argv to access arguments, and fs.readFile or fs.readFileSync to read file content.
const fs = require('fs');
// Non-blocking example with fs.readFile
const fileNames = process.argv.splice(2);
fileNames.forEach(fileName => {
fs.readFile(fileName, 'utf-8', (error, data) => {
if (error) throw error;
console.log(fileName, data);
});
});
// Blocking example with fs.readFileSync
const fileName = fileNames[0];
console.log(fileName, fs.readFileSync(fileName, 'utf-8'));

Categories

Resources