search
HomeWeb Front-endFront-end Q&AHow to determine whether the downloaded network file exists in nodejs

In Node.js, downloading network files is a very common operation. We can use the built-in module of Node.js to achieve this operation. But before implementing it, we need to determine whether the network file exists. This requires using the HTTP module of Node.js to detect the status of network files.

The HTTP module is one of the standard libraries of Node.js, which provides a set of APIs to communicate with HTTP and HTTPS servers. We can use the HTTP module to send requests to the server and obtain response data. Before downloading network files, we must first understand how the HTTP module detects the status of network files.

  1. HTTP module detects network file status

In Node.js, we can use the HTTP module to send a HEAD request to the server to obtain the metadata information of network files. This metadata information includes file size, last modification time, etc. Through this information, we can determine whether the network file exists and obtain relevant information about the network file. The following is a sample code that uses the HTTP module to detect the status of network files:

const http = require('http');
const url = 'http://example.com/sample.txt';

http.request(url, { method: 'HEAD' }, (res) => {
  console.log(res.statusCode);
})
.on('error', (err) => {
  console.error(err);
})
.end();

In the above code, we first introduce the HTTP module and the URL of the network file to be detected. Then, use the http.request() method to send a HEAD request to the server and obtain the server response. After getting the response, we can get the response status code through the res.statusCode property. If the response status code is 200, it means that the network file exists; if the response status code is 404, it means that the network file does not exist. If an error occurs during sending the request, you can capture the error through the .catch() method and print the error information.

  1. Detect and download network files

After determining whether the network file exists, we can use the built-in module fs of Node.js to implement the download operation.

const http = require('http');
const fs = require('fs');
const url = 'http://example.com/sample.txt';
const filePath = './sample.txt';

http.request(url, { method: 'HEAD' }, (res) => {
  if (res.statusCode === 200) {
    const file = fs.createWriteStream(filePath);
    http.get(url, (res) => {
      res.pipe(file);
    });
  } else {
    console.log('File not found.');
  }
})
.on('error', (err) => {
  console.log(err);
})
.end();

In the above code, we first use the HTTP module to send a HEAD request to the server to obtain the status code of the network file. If the status code is 200, it means that the network file exists. Then, we create a Writable Stream (fs.createWriteStream()) and send a GET request to the server through the http.get() method to obtain the network file content. After getting the file contents, we write the file to the local file system (res.pipe(file)).

If the network file does not exist, "File not found." will be output. If an error occurs while sending the HTTP request, an error message will be displayed.

Summary

In Node.js, you can use the HTTP module to detect the status of network files. You can use the HTTP module to send a HEAD request to the server to obtain metadata information about network files. After obtaining the status of the network file, we can use the built-in module fs of Node.js to implement the download operation.

The above is the detailed content of How to determine whether the downloaded network file exists in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering CSS Selectors: Class vs. ID for Efficient StylingMastering CSS Selectors: Class vs. ID for Efficient StylingMay 16, 2025 am 12:19 AM

The use of class selectors and ID selectors depends on the specific use case: 1) Class selectors are suitable for multi-element, reusable styles, and 2) ID selectors are suitable for unique elements and specific styles. Class selectors are more flexible, ID selectors are faster to process but may affect code maintenance.

HTML5 Specification: Exploring the Key Goals and MotivationsHTML5 Specification: Exploring the Key Goals and MotivationsMay 16, 2025 am 12:19 AM

ThekeygoalsandmotivationsbehindHTML5weretoenhancesemanticstructure,improvemultimediasupport,andensurebetterperformanceandcompatibilityacrossdevices,drivenbytheneedtoaddressHTML4'slimitationsandmeetmodernwebdemands.1)HTML5aimedtoimprovesemanticstructu

CSS IDs and Classes : a simple guideCSS IDs and Classes : a simple guideMay 16, 2025 am 12:18 AM

IDsareuniqueandusedforsingleelements,whileclassesarereusableformultipleelements.1)UseIDsforuniqueelementslikeaspecificheader.2)Useclassesforconsistentstylingacrossmultipleelementslikebuttons.3)BecautiouswithspecificityasIDsoverrideclasses.4)Useclasse

HTML5 Goals: Understanding the Key Objectives of the SpecificationHTML5 Goals: Understanding the Key Objectives of the SpecificationMay 16, 2025 am 12:16 AM

HTML5aimstoenhancewebaccessibility,interactivity,andefficiency.1)Itsupportsmultimediawithoutplugins,simplifyinguserexperience.2)Semanticmarkupimprovesstructureandaccessibility.3)Enhancedformhandlingincreasesusability.4)Thecanvaselementenablesdynamicg

Is it difficult to use HTML5 to achieve its goals?Is it difficult to use HTML5 to achieve its goals?May 16, 2025 am 12:06 AM

HTML5isnotparticularlydifficulttousebutrequiresunderstandingitsfeatures.1)Semanticelementslike,,,andimprovestructure,readability,SEO,andaccessibility.2)Multimediasupportviaandelementsenhancesuserexperiencewithoutplugins.3)Theelementenablesdynamic2Dgr

CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!