You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Простой серверimporthttpfrom'http'constserver=http.createServer((req,res)=>{// write status and headersres.writeHead(200,{'Content-Type': 'text/plain'})// send plain textres.write('hi\n')// some jsonconstjson={message: 'bye'}// send jsonres.end(JSON.stringify(json))})server.listen(3000,/* host - localhost or 127.0.0.1 by default */(e)=>{if(e){console.error(e)}console.log('🚀')})// Ответ сервера в виде HTML-файлаconstfilePath=`${__dirname}/index.html`constserver=http.createServer(async(req,res)=>{if(req.url==='/hi'){res.writeHead(200,{'Content-Type': 'text/html'})try{constcontent=awaitfs.readFile(filePath,'utf-8')returnres.end(content)}catch(e){console.error(e)}}res.writeHead(200,{'Content-Type': 'text/plain'})res.write('bye')res.end()})// Ответ сервера в виде аудио-файлаimport{promisesasfs,constants,createReadStream}from'fs'// path to audioconstfilePath=`${__dirname}/audio.mp3`constserver=http.createServer(async(req,res)=>{switch(req.url){case'/': {res.writeHead(200,{'Content-Type': 'text/plain'})res.write('hi')returnres.end()}case'/audio': {try{res.writeHead(200,{'Content-Type': 'audio/mp3'})// check if file existsawaitfs.access(filePath,constants.F_OK)// create read streamconststream=createReadStream(filePath)// create pipereturnstream.pipe(res)}catch(e){res.end('not found')}}}})
Модуль fs
import{join,dirname}from'path'import{fileURLToPath}from'url'import{promisesasfs}from'fs'// absolute path to current working directoryconst__dirname=dirname(fileURLToPath(import.meta.url))// with `join()`constdirPath=join(__dirname,'files')// without `join()`constfilePath=`${dirPath}/message.txt`constcontent='hi'// createtry{// create dirawaitfs.mkdir(dirPath,{recursive: true})// create fileawaitfs.writeFile(filePath,content)console.log('created')}catch(e){console.error(e)}// readtry{constcontent=awaitfs.readFile(filePath,'utf-8')console.log(content)// hi}catch(e){console.error(e)}// appendtry{awaitfs.appendFile(filePath,'\nbye')constcontent=awaitfs.readFile(filePath,'utf-8')console.log(content)// hi \nbye}catch(e){console.error(e)}// removetry{// remove fileawaitfs.unlink(filePath)// remove dirawaitfs.rmdir(dirPath)}catch(e){console.error(e)}
Безопасное создание, чтение и удаление файла
// root pathconstROOT_PATH=`${__dirname}/files`// check if dir or file not existsconstnotExist=(e)=>e.code==='ENOENT'// truncate pathconsttruncPath=(p)=>p.split('/').slice(0,-1).join('/')// createasyncfunctioncreateFile(fileData,filePath,fileExt='json'){constfileName=`${ROOT_PATH}/${filePath}.${fileExt}`try{// create fileawaitfs.writeFile(fileName,JSON.stringify(fileData,null,2))}catch(e){if(notExist(e)){// create dirawaitfs.mkdir(truncPath(`${ROOT_PATH}/${filePath}`),{recursive: true})// create file after dir has been createdreturncreateFile(fileData,filePath,fileExt)}console.error(e)}}// readasyncfunctionreadFile(filePath,fileExt='json'){constfileName=`${ROOT_PATH}/${filePath}.${fileExt}`letfileHandler=nulltry{// open filefileHandler=awaitfs.open(fileName)// read filereturnawaitfileHandler.readFile('utf-8')}catch(e){if(notExist(e)){returnconsole.error('not found')}console.error(e)}finally{// close handlerfileHandler?.close()}}// removeasyncfunctionremoveFile(filePath,fileExt='json'){constfileName=`${ROOT_PATH}/${filePath}.${fileExt}`try{// remove fileawaitfs.unlink(fileName)// remove dirawaitremoveDir(truncPath(`${ROOT_PATH}/${filePath}`))}catch(e){if(notExist(e)){returnconsole.error('not found')}console.error(e)}}// remove dirasyncfunctionremoveDir(dirPath,rootPath=ROOT_PATH){if(dirPath===rootPath)returnconstisEmpty=(awaitfs.readdir(dirPath)).length<1if(isEmpty){// remove dir if its emptyawaitfs.rmdir(dirPath)// remove parent dirremoveDir(truncPath(dirPath),rootPath)}}// get all file namesasyncfunctiongetFileNames(path=ROOT_PATH){letfileNames=[]try{constfiles=awaitfs.readdir(path)if(files.length<1)returnfileNamesfor(letfileoffiles){file=`${path}/${file}`constisDir=(awaitfs.stat(file)).isDirectory()if(isDir){fileNames=fileNames.concat(awaitgetFileNames(file))}else{fileNames.push(file)}}returnfileNames}catch(e){if(notExist(e)){returnconsole.error('not found')}console.error(e)}}