Discussion on NodeJS require path problem

  • 2020-06-07 04:00:41
  • OfStack

The project needs TO use nodejs. I feel that nodejs is the only way to be a full stack engineer, so I start to learn nodejs. Here is the first hello, world program.

1, server. js file, which is equivalent to the server script.


var http = require("http");

function start() {
  function onRequest(request, response) {
    console.log("Request recieved")
    response.writeHead(200, {
      "Content-Type": "text/plain"
    });
    response.write("hello,world");
    response.end();
  }
  http.createServer(onRequest).listen(8888);
}
exports.start=start;

This is the simplest module. http is the built-in module of nodejs and start is the self-defined module.

2, index js. This is the executable file. Note the path to require.


var server=require("./module/server");
server.start();

Run node ES27en.js with node in the project directory, then type http://localhost:8888 in the browser to see the exciting hello, world, and Request recieved in the node terminal. The first program runs successfully.

The above program, module, is the folder that contains the ES39en.js files. index.js is the sibling of the module folder.

Note the require path:

Current directory of relative paths:./xxx/ xxx. js or./xxx/xxx.
Relative path of the parent directory:.. / xxx/xxx js or.. / xxx/xxx.
An absolute path: F: / xxx xxx js or/xxx/xxx js or/xxx xxx.

This is the end of this article, I hope you enjoy it.


Related articles: