const http=require('http');
const fs=require('fs');
http.createServer(function (req, res) {
//Open a file on the server and return its content:
fs.readFile('./index.html',null, (err, data) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8080);
I am newbie in node js.Just started learning nodejs recently.
Getting this error while trying to Reading content of HTML File through Nodejs. I have updated
npm module but it is not working.->
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
←[90m at new NodeError (node:internal/errors:371:5)←[39m
←[90m at write_ (node:_http_outgoing:742:11)←[39m
←[90m at ServerResponse.write (node:_http_outgoing:707:15)←[39m
at ReadFileContext.callback (H:\node\nodetutorial\coremodule\Readingdata.js:8:11)
←[90m at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:314:13)←[39m {
code: ←[32m'ERR_INVALID_ARG_TYPE'←[39m
}
The res.write() function cannot accept an undefined object (which is what you're passing right now). Try stringifying your response like this:
res.write(JSON.stringify(data));
Additionally, check why data is undefined
The path to the ./index.html file is probably incorrect. You can find out what directory you're currently in by executing console.log(__dirname). You can either change the path to the file (eg: ./../index.html) or move the file according to the output.
Related
I have old monolith app written in NodeJS.
It requires lots of node_modules.
Application is exiting, because of unhandled exception which is happening in some of the modules.
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection: undefined
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received type number (22388)
at Object.writeFileSync (node:fs:2146:5)
at ProcessContainer (/usr/lib/node_modules/pm2/lib/ProcessContainer.js:67:8)
at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainer.js:100:3)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
For now I have included this code in hope that it will give me stack trace:
process.on('uncaughtException', (e) => {
logger.error(e.stack || e, `uncaughtException happened`);
process.exit(1);
});
Problem is it takes several days/weeks for error to occur.
Did anyone had similar/same issue?
Is there a way to globally override function of some module?
If this is possible it would be easy for me to create a wrapped function with try catch.
I use NodeJS 14, 16 has same issue. I can't rollaback node version
I will try with this. However I am unsure if it overrided fs.writeFileSync everywhere
import fs from 'fs';
const f = fs.writeFileSync;
delete fs.writeFileSync;
fs.writeFileSync = (fileName, data, options) => {
try {
logger.debug({ fileName }, `Overriding writeFileSync function`);
f(fileName, data, options);
} catch (err) {
logger.error({ err: err.stack || err, fileName }, 'Error in writing file');
}
};
Observed Application Behavior
I'm getting a UnhandledPromiseRejectionWarning: Error: Upload failed when using #google-cloud/storage in node.js.
These errors come when processing thousands of requests. It's a small percentage that cause errors, but due to the lack of ability to handle the errors, and the lack of proper context from the error message, it's very difficult to determine WHICH files are failing.
I know in general promises must have a .catch or be surrounded by a try/catch block. But in this case I'm using a write stream. I'm a little bit confused as to where the promise that's being rejected is actually located and how I would intercept it. The stack trace is unhelpful, as it only contains library code:
UnhandledPromiseRejectionWarning: Error: Upload failed
at Request.requestStream.on.resp (.../node_modules/gcs-resumable-upload/build/src/index.js:163:34)
at emitTwo (events.js:131:20)
at Request.emit (events.js:214:7)
at Request.<anonymous> (.../node_modules/request/request.js:1161:10)
at emitOne (events.js:121:20)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (.../node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
My Code
The code that's creating the writeStream looks like this:
const {join} = require('path')
const {Storage} = require('#google-cloud/storage')
module.exports = (config) => {
const storage = new Storage({
projectId: config.gcloud.project,
keyFilename: config.gcloud.auth_file
})
return {
getBucketWS(path, contentType) {
const {bucket, path_prefix} = config.gcloud
// add path_prefix if we have one
if (path_prefix) {
path = join(path_prefix, path)
}
let setup = storage.bucket(bucket).file(path)
let opts = {}
if (contentType) {
opts = {
contentType,
metadata: {contentType}
}
}
const stream = setup.createWriteStream(opts)
stream._bucket = bucket
stream._path = path
return stream
}
}
}
And the consuming code looks like this:
const gcs = require('./gcs-helper.js')
module.exports = ({writePath, contentType, item}, done) => {
let ws = gcs.getBucketWS(writePath, contentType)
ws.on('error', (err) => {
err.message = `Could not open gs://${ws._bucket}/${ws._path}: ${err.message}`
done(err)
})
ws.on('finish', () => {
done(null, {
path: writePath,
item
})
})
ws.write(item)
ws.end()
}
Given that I'm already listening for the error event on the stream, I don't see what else I can do here. There isn't a promise happening at the level of #google-cloud/storage that I'm consuming.
Digging into the #google-cloud/storage Library
The first line of the stack trace brings us to a code block in the gcs-resumable-upload node module that looks like this:
requestStream.on('complete', resp => {
if (resp.statusCode < 200 || resp.statusCode > 299) {
this.destroy(new Error('Upload failed'));
return;
}
this.emit('metadata', resp.body);
this.deleteConfig();
this.uncork();
});
This is passing the error to the destroy method on the stream. The stream is being created by the #google-cloud/common project's utility module, and this is using the duplexify node module to create the stream. The destroy method is defined on the duplexify stream and can be found in the README documentation.
Reading the duplexify code, I see that it first checks this._ondrain before emitting an error. Maybe I can provide a callback to avoid this error being unhandled?
I tried ws.write(item, null, cb) and still got the same UnhandledPromiseRejectionWarning. I tried ws.end(item, null, cb) and even wrapped the .end call in a try catch, and ended up getting this error which crashed the process entirely:
events.js:183
throw er; // Unhandled 'error' event
^
Error: The uploaded data did not match the data from the server. As a precaution, the file has been deleted. To be sure the content is the same, you should try uploading the file again.
at delete (.../node_modules/#google-cloud/storage/build/src/file.js:1295:35)
at Util.handleResp (.../node_modules/#google-cloud/common/build/src/util.js:123:9)
at retryRequest (.../node_modules/#google-cloud/common/build/src/util.js:404:22)
at onResponse (.../node_modules/retry-request/index.js:200:7)
at .../node_modules/teeny-request/build/src/index.js:208:17
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
My final code looks something like this:
let ws = gcs.getBucketWS(writePath, contentType)
const handleErr = (err) => {
if (err) err.message = `Could not open gs://${ws._bucket}/${ws._path}: ${err.message}`
done(err)
}
ws.on('error', handleErr)
// trying to do everything we can to handle these errors
// for some reason we still get UnhandledPromiseRejectionWarning
try {
ws.write(item, null, err => {
handleErr(err)
})
ws.end()
} catch (e) {
handleErr(e)
}
Conclusion
It's still a mystery to me how a user of the #google-cloud/storage library, or duplexify for that matter, is supposed to perform proper error handling. Comments from library maintainers of either project would be appreciated. Thanks!
Update :
The issue was solved after a clean installation of NodeJS.
I am trying to create a PDF file downloader in NodeJS. This is my code
const file = fs.createWriteStream(filePath);
const sendReq = request.get(pdfUrl);
sendReq.on('response', (response) => {
if (response.statusCode !== 200) {
reject()
}
sendReq.pipe(file);
});
file.on('finish', () => {
file.close()
resolve()
});
sendReq.on('error', (err) => {
console.log(err)
fs.unlink(file);
reject()
});
This is the error I'm getting :
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function
at _addListener (events.js:180:11)
at WriteStream.addListener (events.js:240:10)
at WriteStream.close (fs.js:2302:10)
at WriteStream.<anonymous> (/var/www/html/lottery-api/app/Helpers/DocumentHelper.js:25:30)
at WriteStream.emit (events.js:164:20)
at finishMaybe (_stream_writable.js:605:14)
at afterWrite (_stream_writable.js:456:3)
at onwrite (_stream_writable.js:446:7)
at fs.js:2246:5
at FSReqWrap.wrapper [as oncomplete] (fs.js:703:5)
I'm using ubuntu 16.04 with
Node : v10.15.0
If I remove this code, there are no errors
file.on('finish', () => {
file.close()
resolve()
});
I'm using pdfreader package to parse the saved pdf file.
If remove above code I can't handle the callback properly and the pdf reader produces an error.
Below is the error :
(while reading XRef): Error: Invalid XRef stream XRefParseException
data: 'An error occurred while parsing the PDF: InvalidPDFException',
What am I doing wrong?
The same code works fine in MacOS Mojave 10.14 with node v10.15.0.
I am trying to create a proxy update code with node.js, and im getting this error:
events.js:180
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function');
^
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function
at _addListener (events.js:180:11)
at WriteStream.addListener (events.js:240:10)
at WriteStream.close (fs.js:2298:10)
at WriteStream.<anonymous> (/Users/camden/Desktop/proxyupdate/u.js:9:15)
at WriteStream.emit (events.js:164:20)
at finishMaybe (_stream_writable.js:616:14)
at afterWrite (_stream_writable.js:467:3)
at onwrite (_stream_writable.js:457:7)
at fs.write (fs.js:2242:5)
at FSReqWrap.wrapper [as oncomplete] (fs.js:703:5)
here is my code:
var UpdateProxyList = function(sourceURL, destinationPath) {
var HTTP = require("http");
var FS = require("fs");
var File = FS.createWriteStream(destinationPath);
HTTP.get(sourceURL, function(response) {
response.pipe(File);
File.on('finish', function() {
File.close();
});
File.on('error', function(error) {
FS.unlink(destinationPath);
})
});
}
UpdateProxyList("http://www.example.com/proxy.txt", "myproxylist.txt");
Im on MacOS Sierra with node.js v9.3.0.
apparently, when I use node.js v8.9.3, it works fine
Between v8.9.3 and v9.3.0, the implementation of WriteStream.prototype.close has changed.
In v8.9.3, it was a reference to ReadStream.prototype.close, for which a callback argument was optional.
In v9.3.0, it is now a separate method that, amongst other things, emits a close event:
WriteStream.prototype.close = function(cb) {
if (this._writableState.ending) {
this.on('close', cb);
return;
}
...
};
The error that you get is caused by this.on('close', cb), which requires a Function second argument that isn't being passed in your code.
I'm not sure if you actually need to use a finish handler at all in your situation, as writable handling will be done internally by the .pipe() code.
Hi I am trying to call a simple web API which returns a string as response. I want to use node for this. Since I am new to node so I tried reffering to many blog post and got a code snippet which I used but I am getting same error for all urls whether its google.com or anything else.
My Node code is as follows
var http = require('http');
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Error:
F:\nodejs>node ..\NodeLearning\TestServer1\test.js
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Can Any one tell me what has gone wrong here?
Can you try one more time by setting a proxy like mentioned below
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new',
proxy:'add your proxy setting'
};