简体   繁体   English

Node.js中的TCP套接字和文件操作

[英]TCP sockets and file manipulation in Node.js

I am new to Node.js and I have 2 questions about it: 我是Node.js的新手,对此有2个问题:

  • Can you create regular TCP sockets on the server's side? 您可以在服务器端创建常规的TCP套接字吗?
  • Is it possible to read/write to a file on the server's side? 是否可以在服务器端读取/写入文件?

That's all. 就这样。 Both of these are critical for putting my program on the web. 这两者对于将我的程序发布到网络上都是至关重要的。

Node has inbuilt modules that have the functionality you're looking for. Node具有内置模块,这些模块具有您要寻找的功能。 You can create raw TCP sockets on the server side with the native net module. 您可以使用本机net模块在服务器端创建原始TCP套接字。

var net = require('net');
net.createServer(function(socket) {
  socket.write('data');
  socket.end();
});

And there is also a fs module for file system manipulation: 还有一个用于文件系统操作的fs模块:

var fs = require('fs');

var data = 'a string';
var file = './file';

fs.writeFile(file, data, function(err) {
  if (err) throw err;
  // file has been written to disk
});

// or synchronously writing a file
fs.writeFileSync(file, data);

// fetch the data asynchronously
fs.readFile(file, function(err, data) {
  // we have "a string"
});

// synchronously reading a file
var str = fs.readFileSync(file);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM