最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the source of this error attempting to read my local html file using Node.js? - Stack Overflow

programmeradmin0浏览0评论

This is all happening on my one machine -- both the server and the client machine are the same. I am learning on w3schools and have successfully completed the Node.js examples in order until this one where I am attempting to read an html file to use as content to display. The server starts correctly as seen in the console with the blinking cursor like the prior examples, however upon trying to access localhost through chrome, I get the console logged error as well as a notification in chrome with "127.0.0.1 refused to connect."

error:

node:_http_outgoing:949
    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 write_ (node:_http_outgoing:949:11)
    at ServerResponse.write (node:_http_outgoing:904:15)
    at ReadFileContext.callback (C:\path-to-file-omitted\demo_readfile.js:7:9)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:299:13) {
  code: 'ERR_INVALID_ARG_TYPE'
}

Node.js v22.13.0

The two files verbatim as I used them from w3schools.

demofile1.html

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

demo_readfile.js

var http = require('http');
var fs = require('fs');



http.createServer(function (req, res) {
  fs.readFile('demofile1.html', function(err, data) { // read the html file
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data); // write the html content to the view
    return res.end();
  });
}).listen(8080);

Using Powershell to start node.js instance with my file using 'node C:\path-to-file\filename.js', I tried running powershell as an admin. I tried doing some searches on google and stack overflow to identify this error elsewhere, and while they appeared similar, the ones I found did not apply directly to my issue as far as I know, nor did they at least give me a resolution.

This is all happening on my one machine -- both the server and the client machine are the same. I am learning on w3schools and have successfully completed the Node.js examples in order until this one where I am attempting to read an html file to use as content to display. The server starts correctly as seen in the console with the blinking cursor like the prior examples, however upon trying to access localhost through chrome, I get the console logged error as well as a notification in chrome with "127.0.0.1 refused to connect."

error:

node:_http_outgoing:949
    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 write_ (node:_http_outgoing:949:11)
    at ServerResponse.write (node:_http_outgoing:904:15)
    at ReadFileContext.callback (C:\path-to-file-omitted\demo_readfile.js:7:9)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:299:13) {
  code: 'ERR_INVALID_ARG_TYPE'
}

Node.js v22.13.0

The two files verbatim as I used them from w3schools.

demofile1.html

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

demo_readfile.js

var http = require('http');
var fs = require('fs');



http.createServer(function (req, res) {
  fs.readFile('demofile1.html', function(err, data) { // read the html file
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data); // write the html content to the view
    return res.end();
  });
}).listen(8080);

Using Powershell to start node.js instance with my file using 'node C:\path-to-file\filename.js', I tried running powershell as an admin. I tried doing some searches on google and stack overflow to identify this error elsewhere, and while they appeared similar, the ones I found did not apply directly to my issue as far as I know, nor did they at least give me a resolution.

Share Improve this question edited Jan 20 at 18:44 LifeAsPixels asked Jan 20 at 17:49 LifeAsPixelsLifeAsPixels 94 bronze badges 9
  • 1 The first parameter to the fs.readFile callback has the details of the error. if(err) { console.log("Error reading file:", err); } – Guy Incognito Commented Jan 20 at 17:57
  • "using 'node C:\path-to-file\filename.js'" - If you're running the server from a different working directory then the relative pathname for opening the file may be incorrect. Try running the server from within the directory and/or specifying a complete file path when reading the file. – David Commented Jan 20 at 18:08
  • @David Thanks for the response. They are running from the same directory. – LifeAsPixels Commented Jan 20 at 18:45
  • @LifeAsPixels: In that case can you: (1) Test running with simply node filename.js and see if the behavior changes (even if it fails, it may fail in a different way); (2) Check the content of err in the callback to the fs.readFile() operation to see what error is occurring when trying to read the file. – David Commented Jan 20 at 18:47
  • @David do you mean via the intellisense pop-up? This is what it says, seems unrelated... "'err' is declared but its value is never read.ts(6133) (parameter) err: any" – LifeAsPixels Commented Jan 20 at 18:58
 |  Show 4 more comments

3 Answers 3

Reset to default 1

The code you've provided is indeed correct. The problem is that you use absolute paths which is confusing for the filesystem module.
To avoid errors like this, you can move your HTML file and JS scripts to one directory and run them using node demo_readfile.js instead of node C:\something\demo_readfile.js. Even better thing to do is use a filesystem path utility module, like this:

const http = require("http");
const path = require("path");
const fs = require("fs");

http.createServer(function (req, res) {

  fs.readFile(path.join(__dirname, "demofile1.html"), function(err, data) {

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();

  });

}).listen(8080);

The above code utilizes path.join() to ensure that fs.readFile() always navigates to the correct path, no matter from where the script is called (which is useful when working with larger projects, eg. when the helper function file is located elsewhere than the index).

Changing the powershell working directory to the javascript and html file location and starting the server with 'node filename.js' solves the problem instead of using absolute path to start the server. Attributed to David in the comments from the original post.

Because you're new one so lets break this down: From your error console, pay attention to the line point to your code:

at ReadFileContext.callback (C:\path-to-file-omitted\demo_readfile.js:7:9)

This means the error is spotted in the line 7, char 9th. Next, read the error:

The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined

So combine both, I think that your data is undefined right now and you're trying to write the undefined and return to the browser.

Then the solutions you should try:

  1. Check the path. Ensure what you put as first argument of fs.readFile is your correct path and file name. Your should put 2 files at the same folder.
  2. Try to log your data before turn it to browser: add console.log(data) before the line res.writeHead...
发布评论

评论列表(0)

  1. 暂无评论