the terminal is showing >>>
node:_http_outgoing:862
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at new NodeError (node:internal/errors:399:5)
at write_ (node:_http_outgoing:862:11)
at ServerResponse.write (node:_http_outgoing:827:15)
at ReadFileContext.callback (c:\Users\me\Documents\Web Devolopment Challenge\intro\sample-server.js:7:9)
at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:324:13) {
code: 'ERR_INVALID_ARG_TYPE'
}
Node.js v18.14.1
this is my code
var http = require('http')
var fs = require('fs')
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(7000);
and this is my html code
<html>
<h1>hello guys</h1>
<h2>heyy</h2>
</html>
Related
Below is my code:
const http = require('http');
const fs = require('fs');
http.createServer(testfunc)
.listen(3333);
function testfunc(req,res) {
if (req.method === 'GET'){
fs.readFile('index.html', function(err,data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.write("Hi");
});
res.end();
};
};
I am getting error as below when I send get request to /. Can you let me know what is the issue. If remove res.end() is working fine. But what's wrong in writing res.end().
events.js:292
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at write_ (_http_outgoing.js:629:17)
at ServerResponse.write (_http_outgoing.js:621:15)
at C:\Users\C5218529\3D Objects\RestApi\node-shop-sql\server.js:12:8
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3) Emitted 'error' event on
ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:684:7)
at processTicksAndRejections (internal/process/task_queues.js:85:21) { code:
'ERR_STREAM_WRITE_AFTER_END' }
res.end(); should be after res.write("Hi"); inside callback function fs.readFile().
Because callback function executes later (res.write) and res.end() is executing first.
We cannot write to response after we call res.end() statement.
fs.readFile('index.html', function(err,data){
// these callback statements will be executed later
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.write("Hi");
res.end();
});
// statements below will be executed immediately after fs.readFile as it is async
This app is to get small piece of data from open weather map through api, app.js:
const express = require("express");
const https = require('https');
const app = express();
app.get("/", function (req, res) {
const url = "https://api.openweathermap.org/data/2.5/weather?q=Khartoum&appid=d244334364579178494bb3c4528e218b&units=metric"
https.get(url, function (response) {
response.on("data", function (data) {
const weatherData = JSON.parse(data);
res.write(weatherData.weather[0].description);
res.write(weatherData.weather[0].id);
res.send();
});
});
});
app.listen("3000", function () {
console.log("runnign on port 3000.");
});
the error that triggered in terminal when I reloaded the page:
_http_outgoing.js:671
throw new ERR_INVALID_ARG_TYPE('first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received type number (804)
at write_ (_http_outgoing.js:671:11)
at ServerResponse.write (_http_outgoing.js:636:15)
at IncomingMessage.<anonymous> (/home/foola/Desktop/appBrewery/WeatherProject/app.js:18:17)
at IncomingMessage.emit (events.js:315:20)
at IncomingMessage.Readable.read (_stream_readable.js:512:10)
at flow (_stream_readable.js:985:34)
at resume_ (_stream_readable.js:966:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ERR_INVALID_ARG_TYPE'
So what's the wrong here exactly?
mybe weatherData.weather[0].id is a number type likely integer?
try
res.write(weatherData.weather[0].id+'');
As the error message indicated, res.write accepts buffer or string only, weatherData.weather[0].id is of type int/number, therefore you might want to stringify it first before passing it to res.write.
res.write(weatherData.weather[0].id.toString())
Hi i am just trying to learn node js and i am trying to upload a file to different location in my computer but i am facing some issues...Here is my code...
var http = require('http');
var fs = require('fs');
var formidable = require('formidable');
http.createServer(function(req,res){
if(req.url == '/upload'){
var form = new formidable.IncomingForm();
form.parse(req,function(err,fields,files){
var oldpath = files.filetoupload.path;
var newpath = 'E:/Node/ResumeUpload/' + files.filetoupload.name;
fs.rename(oldpath,newpath,function(err){
if(err) console.log(err);
res.write('File uploaded sucessfully to ' + newpath);
res.end();
})
});
}
else{
fs.readFile('FileUpload.html',function(err,data){
res.writeHead(200,{'Content-Type' : 'text/html'});
res.write(data);
res.end();
});
}
}).listen(9090);
But the problem is it is showing error as below
var oldpath = files.filetoupload.path;
TypeError: Cannot read property 'path' of undefined
at E:\Node\FileUploading.js:8:46
at IncomingForm.<anonymous> (E:\Node\node_modules\formidable\lib\incoming_form.js:107:9)
at emitNone (events.js:106:13)
at IncomingForm.emit (events.js:208:7)
at IncomingForm._maybeEnd (E:\Node\node_modules\formidable\lib\incoming_form.js:557:8)
at E:\Node\node_modules\formidable\lib\incoming_form.js:238:12
at WriteStream.<anonymous> (E:\Node\node_modules\formidable\lib\file.js:79:5)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at WriteStream.emit (events.js:208:7)
Can anybody suggest what would be the reason for this issue...!!
Thank You.
You can use try module multer in nodejs, you can upload file, you can see:Multer
//install multer
$ npm install --save multer
I am using multiparty. It was working fine but suddenly it is throwing error.
Error
err: { Error: stream ended unexpectedly
at Form.<anonymous> (/user_code/node_modules/multiparty/index.js:754:24)
at emitNone (events.js:91:20)
at Form.emit (events.js:185:7)
at finishMaybe (_stream_writable.js:514:14)
at endWritable (_stream_writable.js:524:3)
at Form.Writable.end (_stream_writable.js:489:5)
at onend (_stream_readable.js:511:10)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9) status: 400, statusCode: 400 }
Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var multiparty = require('multiparty');
var http = require('http');
var util = require('util');
exports.helloWorld = functions.https.onRequest((request, response) => {
var body = "";
var POST = {};
var form = new multiparty.Form();
form.on('error', function(err) {
console.log('Error parsing form: ' + err.stack);
});
form.parse(request, function(err, fields, files) {
response.status(500).send({
message: err
});
})
});
});
The "stream ended unexpectedly" error implies the underlying TCP socket was closed before a complete multipart form was received.
As you say this was previously working you should check the server to which you are making the request for any errors which may be closing the response early. One common cause is the size of the response data being larger than accepted by the server or request/response headers.
I am new in NodeJS, and I am working an an example:
function test(req,res){
var path = urls[Math.floor(Math.random()*urls.length)];
console.log("try to redirect to:"+path);
http.get(path,function(res_server){
//how to send the data from res_server to res
});
}
And the urls is an array of url.
I wonder how can I send the data from the res_server to the original client response?
BTW, the url maybe http or https.
update
var urls=["url1","url2","url3"];
var path = urls[Math.floor(Math.random()*urls.length)]; // find an random item from the array
update:2
Fine, this is the complete simple test script:
var http=require("http");
http.createServer(function(req, res1) {
var url = 'http://www.google.com.hk/images/srpr/logo11w.png';
var hp=require("http");
hp.get(url, function(res2) {
res2.pipe(res1);
});
}).listen(3000);
It works, but if you change http://www.google.com.hk/...logo..png to https:/www.google.....png
It will throw error:
http.js:1840
throw new Error('Protocol:' + options.protocol + ' not supported.');
^
Error: Protocol:https: not supported.
at Object.exports.request (http.js:1840:11)
at Object.exports.get (http.js:1847:21)
at Server.<anonymous> (C:\Users\maven\Desktop\t.js:6:6)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:525:27)
Change var http = require('http'); to var http = require('https');
I do not fully understand your example. Looks strange to me. However best would be to pipe the request response into the server response:
http.createServer(function(req, res1) {
var path = url.format({
protocol: 'http:',
host: 'www.google.com'
});
http.get(path, function(res2) {
res2.pipe(res1);
});
}).listen(3000);