NODE Js: Wrong file type generating? - node.js

I want to create mp3 file with words I have given it programmatically. I am using Google Text-To-Speech API to convert into .mp3. Code working fine and its also generating file test.mp3 but not in the original format of .mp3 (It is looks like a .mp3 file and cannot open). Can anyone help me on the same.
My code is:
var fs = require('fs');
var request = require('request');
var text = 'Hello World';
var options = {
url: 'http://translate.google.com/translate_tts?ie=UTF-8&q=' + encodeURIComponent(text) + '&tl=en&client=t',
headers: {
'Referer': 'http://translate.google.com/',
'User-Agent': 'stagefright/1.2 (Linux;Android 5.0)'
}
}
request(options)
.pipe(fs.createWriteStream('test.mp3'))

I got the answer-
just change the url , use simply +text+ not +encodeURIComponent(text)+
url: 'http://translate.google.com/translate_tts?ie=UTF-8&q=' + encodeURIComponent(text) + '&tl=en&client=t'
I dont know why encodeURIComponent() is not working. Luckly fixed right now.

Related

How to download a multipart wav file from cloudant database and save locally using Node JS and REST API?

I am stuck in retrieving multipart from cloudant using Node JS API. Hence, I used REST API to download the wav file from cloudant database. But its not downloading wav file from https URL. When I enter the https URL directly in browser, it prompts me to save file locally. So, the URL is correct.
Here is the code for REST API:
var request1 = require('request');
var filestream = fs.createWriteStream("input.wav");
var authenticationHeader = "Basic " + new Buffer(user + ":" + pass).toString("base64");
request1( { url : "example.com/data/1533979044129/female";, headers : { "Authorization" : authenticationHeader } },
function (error, httpResponse, body) {
const statusCode = httpResponse.statusCode;
httpResponse.pipe(filestream);
httpResponse.on('end', function () {
console.log("file complete");
filestream.close();
}); });
The file size of input.wav is 0. Its not downloading file. Please help.
Your callback has an error argument, which you are completely ignoring. Do something with this error, like print it out so your problem can tell you what you're doing wrong. I definitely see at least 1 problem in your source, and the error from request should tell you what it is.
Edit On second thought the above code shouldn't even execute. You should share code that you tested yourself. There's typos in there.

POST request to retrieve pdf in node.js

I am making a POST request to retrieve a pdf. The request works fine if I do it in postman, but I get an empty pdf if I do it through node.js using the request package. Here's my request using the request package:
let body = {
attr1: "attr1",
attr2: "attr2"
}
let opts = {
url: "some_url",
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body
}
request(requestOpts).then(pdf => {
console.log(pdf) // prints out the binary version of the pdf file
fs.writeFileSync("testing.pdf", pdf);
});
I use the exact same request parameters when I use postman but it returns the pdf w/ the correct content.
Can someone help? Or is the way I am saving my pdf incorrect?
Thanks in advance!
Solution - i had to set encoding: false in the request options.
Try
fs.writeFileSync("testing.pdf", pdf, 'binary');
The third argument here tells fs to write binary rather than trying to UTF-8 encode it.
According to the docs the third paramter should be a string that represents the encoding.
For pdf files the encoding is 'application/pdf'
So this should work for you : fs.writeFileSync("testing.pdf", pdf, 'application/psf');

How do I send a buffer in an HTTP request?

I have a file in memory (buffer) - there is no file on the file system.
I want to send that buffer to another server that talks HTTP.
For example, some API A creates a file in memory, SignServer manipulates such files, and responds with a new buffer. My API takes the file from A and feeds it to SignServer.
I tried sending the file to SignServer in multiple ways, but it keeps responding with status 400 (missing field 'data' in request).
What I tried:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
workerName: 'PDFSigner',
data: file_buffer
});
var request = new http.ClientRequest({
hostname: 'localhost',
port: 8080,
path: '/signserver/process',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// I also tried 'multipart/form-data'
'Content-Length': Buffer.byteLength(data)
}
});
request.end(data);
I tried printing data, and it showed:
workerName=PDFSigner&data=
Which is bad because data wasn't set to file_buffer.
I tried printing file_buffer, and it does have content (not null, not undefined, actually has bytes inside).
So stringifying the buffer gave an empty string.
I tried doing the same thing with the request module and it didn't work either.
Note that SignServer isn't written in Node nor JavaScript. It's a Java application, so it probably doesn't work with json (which is why I'm trying to do it with querystring). Yes, I tried sending json.
The reason why data is set to an empty string is described in this issue and the solution is given in this issue.
escape and stringify the buffer like so:
var data = querystring.stringify({
workerName: 'PDFSigner',
data: escape(file_buffer).toString('binary')
});
As #robertklep mentioned, your other problem is that you can't send a big file using application/x-www-form-urlencoded. You'd need to do it with multipart/form-data.

File Corruption when Uploading Excel files to Microsoft Graph API Beta

We're trying to upload Microsoft Excel file to OneDrive but the file gets corrupted every time we do so.
We've tried using [these instructions] to make a PUT request to the following permutations of settings:
Content-Encodings:
text/plan
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
POST bodies:
XLSX file bytes raw from disk
XLSX file encoded as UTF8 string
XLSX file encoded as base64
If we download the file that gets uploaded, it looks almost the same, but a few binary regions are different.
If you feel comfortable opening an Excel file off the internet, I've uploaded an example of the file we upload and the corrupted file OneDrive saves.
This has all the smell of a bug that can be fixed with a single parameter modification... I just can't figure out what it is.
Anyone have thoughts? Thanks!
Thanks #GSM. Here's our code in TypeScript.
var fileContent = FileSystem.readFileSync(localFile);
var url = `https://graph.microsoft.com/beta/me/drive/root/children/${doc.name}.xlsx:/content`,
var opts {
url: url,
method: 'PUT',
headers: [
'Content-Type': 'text/plain',
'Authorization': token
],
body: fileContent
};
var requestOpts = {
url: `https://${domain}${opts.path}`,
method: opts.method,
headers: {},
};
request(opts, cb);
The only difference I see is that you're using an alternate path to upload the file, which is also documented on the GraphAPI page. If we use the path you're using we get back the back the error message:
{
"error": {
"code": "BadRequest",
"message": "Entity only allows writes with a JSON Content-Type header.",
"innerError": {
"request-id": "2a2e7588-3217-4337-bee3-f8aff208510c",
"date": "2016-05-30T16:35:50"
}
}
}
..which is strange because it makes me expect that your code shouldn't have worked either.
Update -- the answer
By reading the file into a string and then writing it to the JSON object that defined the PUT parameters, we were corrupting it. We solved the problem by simply piping a file read stream right to the open HTTP request.
It would be easier to help if you posted your code.
However, here's some code that can be used to upload files to OneDrive. I tested it with your file and was able to upload and download just fine:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.AccessToken);
var byteContent = File.ReadAllBytes(#"C:\Temp\sheet-uploaded.xlsx");
var url = resource + "beta/me/drive/root:/Documents/sheet-uploaded.xlsx:/content";
var result = client.PutAsync(url, new ByteArrayContent(byteContent)).Result;
result.Content.ReadAsStringAsync().Dump();
}

Converting from Windows-1255 to UTF-8 in Node JS

I'm extracting text from a Windows-1255-encoded webpage using Node.js. I'm trying to decode the text using the windows-1255.
After installing it using NPM and requiring it in the relevant file, I tried using it like this:
var title = windows1255.decode('#title').text());
This doesn't seem to have any effect. Any idea why?
Thanks!
Morgan
don't know if you still waiting for an answer about this issue, but the following worked for me...
When fetching the data (a file), I set the get options of encoding to be binary:
var options = {
method: 'GET',
url: 'myURL',
encoding: 'binary'
};
request(options, function (error, response, body) {
//deal with hebrew encoding
csvString = encoding.convert(body, 'UTF8', "CP1255").toString();
Then for I switch encoding from CP1255 (=windows1255) to UTF8.
Hope it helps :)

Resources