Use pipe with Electron ClientRequest module - node.js

I would like download an file with Electron and save my file in path.
So, i've my request with net module, createWriteStream with my path :
const out = fs.createWriteStream(configuration.localFile);
const request = net.request(arg);
request.pipe(out); // Error: request.pipe is not a function
request
.on('response', ...
In the ClientRequest doc, i see ClientRequest implements the Writable Stream interface and is therefore an EventEmitter.
Anyone can help me ?
Thank you community !

Related

Error when attempting to PUT file to URL with Node request

I am trying to PUT a file to an S3 pre-signed URL. Doing so with bash/cURL works fine but with Node I am getting the following error:
Error: write EPIPE
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16) {
errno: -32,
code: 'EPIPE',
syscall: 'write'
}
Here is the code
const fs = require('fs');
const request = require('request');
stream = fs.createReadStream('/tmp/file');
r = request.put('https://s3.eu-west-2.amazonaws.com/bucketname/path?X-Amz-Content-Sha256=....&...');
stream.pipe(r).on('error', function(err) {
console.log(err);
});
EPIPE means that the writing request failed because the other end closed the connection. Looks like there might be some additional settings required inorder to work with amazon s3. I know that curl has native support for multipart/form-data. You can use this library to create readable multipart/form-data streams.
https://nicedoc.io/form-data/form-data
Or you can use third party libraries to send data
https://www.npmjs.com/package/s3-upload-stream
https://www.npmjs.com/package/streaming-s3

How to store image from url to server folder using node js?

I am new to NodeJS and try to practice file upload from URL like this:
I have One url on which one image is placed. I want to upload that image into my server without download it anywhere. How can I do that ?
I tried node-fetch package to fetch buffer of image from URL and then try to write in my server using createWriteStream But failed.
Please help me. I don't know what is the correct way to upload file.
What I have tried :
import { createWriteStream } from 'fs';
import { pipeline } from 'stream';
import { promisify } from 'util'
import fetch from 'node-fetch';
const streamPipeline = promisify(pipeline);
const response = await fetch('http://dummy.com/5.png');
if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);
await streamPipeline(response.body, createWriteStream('./img.png'));

Uncaught TypeError: fs.readFile is not a function

Node.js, Webpack
In this project using webpack, where installed FS.
This code need to read file, but returns error "Uncaught TypeError: fs.readFile is not a function"
const bookForm = document.querySelector(".book-form");
const select = document.querySelector(".select"); const fs = require("fs");
export function abc() { bookForm.addEventListener("submit", e => {
console.log(select.options[select.selectedIndex].text);
e.preventDefault();
fs.readFile("file.txt", function(error, data) {
console.log("file read");
if (error) throw error;
console.log(data); });
}); }
You cannot import the fs module in the browser, because the browser environment does not have access to the user's file system. fs is only available in the Node.js context (on the server) but not on the client (browser).
If you want to send files from the browser to the server, you can use <input type="file"> and let the user manually select the files they have to send. If you want to send a server file's contents to the browser, you can use HTTP communication (AJAX) or you can render it's content in a server-side computed HTML template.
Within your config file you can set the way in which assests like your txt file is uploaded. Then you simply use require('file.txt') to load it - no need to use fs.

React gives Error: not supported error when I try and import local module

I have a local module (speech.js) in my create-react-app src folder that is the google text to speech code on their website. I adjusted it to be an arrow function and use that specific export syntax.
const textToSpeech = require('#google-cloud/text-to-speech');
// Import other required libraries
const fs = require('fs');
const util = require('util');
export const main = async () => {
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
// 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('output.mp3', response.audioContent, 'binary');
console.log('Audio content written to file: output.mp3');
};
What I'm not understanding is why this syntax isn't working in App.js.
import {main} from './speech';
I get the error, Error: not support and "4 stack frames were collapsed". Quite informative!
Does anyone know what the error could be here? I thought as long as I used es6 style imports and exports I wouldn't receive errors. Could this be due to the first require() statement of speech.js? Any help would be appreciated. I've felt like banging my head against the wall for the past 40 minutes.
May not be the correct answer but I believe it has a good chance of being right. I believe that since node is just a runtime environment and not a part of the actual browser, you aren't able to use node modules with react (a frontend framework). The solution to this quandary would be to use something like electron.

How to pass PDFKit readable stream into request's post method?

My app needs to create a PDF file and then upload it to another server. The upload happens down the line via the post method from the request NPM package. Everything works fine if I pass in an fs.createReadStream:
const fs = require('fs');
const params = {file: fs.createReadStream('test.pdf')};
api.uploadFile(params);
Since PDFKit instantiates a read stream as well, I'm trying to pass that directly into the post params like this:
const PDFDocument = require('pdfkit');
const doc = new PDFDocument();
doc.text('steam test');
doc.end();
const params = {file: doc};
api.uploadFile(params);
However, this produces an error:
TypeError: Path must be a string. Received [Function]
If I look at PDFKit source code I see (in coffeescript):
class PDFDocument extends stream.Readable
I'm new to streams and it's clear I'm not understanding the difference here. To me if they are both readable streams, they should both be able to be passed in the same way.

Resources